【问题标题】:HasForeignKey relationship through a Complex Type property通过复杂类型属性的 HasForeignKey 关系
【发布时间】:2014-10-01 07:53:33
【问题描述】:

我有两种复杂类型:

public class ProductItemIdentifier
{
    public Guid Product_Id { get; set; }
    public string ItemName { get; set; }
}

public class AuctionItemIdentifier
{
    public Guid Auction_Id { get; set; }
    public string ItemName { get; set; }
}

我有一个实体类型:

public class Comment
{
    public Guid Id { get; set; }
    public string Comment { get; set; }

    public ProductItemIdentifier ProductItem { get; set; }
    public AuctionItemIdentifier AuctionItem { get; set; }

    #region Navigation

    public virtual Product Product { get; protected set; }
    public virtual Auction Auction { get; protected set; }

    #endregion
}

这里是Configuration

public class CommentConfiguration : EntityTypeConfiguration<Comment>
{
    HasKey(p => p.Id);

    HasOptional(p => p.Product).WithMany().HasForeignKey(p => p.ProductItem.Product_Id).WillCascadeOnDelete(false);
    HasOptional(p => p.Auction).WithMany().HasForeignKey(p => new { p.AuctionItem.Auction_Id }).WillCascadeOnDelete(false);
}

基本上我正在尝试通过复杂类型属性创建外键(但不起作用)。

我得到的错误是:

The properties expression 'p => p.ProductItem.Product_Id' is not valid. The expression should represent a property: C#: 't => t.MyProperty'  VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }'  VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.

有没有什么方法可以创建关系直接将外键列添加到Comment 实体?

【问题讨论】:

    标签: c# entity-framework entity-framework-6 ef-fluent-api


    【解决方案1】:

    这是不可能的。异常已明确表示。

    表达式应该表示一个属性:C#: 't => t.MyProperty'

    它必须是一个简单的属性。

    public class Comment
    {
        ...
    
        public Guid Product_Id { get; protected set; } // simple property
        public virtual Product Product { get; protected set; }
    }
    

    配置。

    HasOptional(p => p.Product)
        .WithMany()
        .HasForeignKey(p => p.Product_Id) // satisfies the C#: 't => t.MyProperty'
        .WillCascadeOnDelete(false);
    

    [ComplexType] 标记ProductItemIdentifier 类也无济于事。

    【讨论】:

      【解决方案2】:

      我的解决方案是创建一些虚拟对象

      public Guid AuctionItem_Auction_Id 
              {
                  get { return AuctionItem.Auction_Id; }
                  set { AuctionItem.Auction_Id = value; }
              }
      
          [ForeignKey("AuctionItem_Auction_Id")]
          public virtual Auction Auction { get; protected set; }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多