【问题标题】:loading mapping table as an entity in entity framework将映射表作为实体加载到实体框架中
【发布时间】:2012-10-23 23:05:56
【问题描述】:

这是采用代码优先方法的最新实体框架。 一位客户可以拥有多个属性:

public class Customer
{
    [Key]
    public int Id { get; set; }
    public virtual List<CustomerToPropertyMapping> PropertyIds { get; set; }
}   

[Table("CustomerToProperty")]
public class CustomerToPropertyMapping
{
    [Key, Column(Order = 1)]
    public int PropertyId { get; set; }
}

当我加载数据时,一切正常。当我试图拯救客户时,我得到了

保存不公开外键的实体时出错 他们关系的属性。 EntityEntries 属性将 返回 null,因为无法将单个实体标识为源 的例外。可以进行保存时的异常处理 通过在实体类型中公开外键属性更容易。看 InnerException 了解详情。

即使我有同样的事情

[Key, Column(Order = 0)]
CustomerId 

在 CustomerToPropertyMapping 类中。

检索映射而不是映射到的对象的正确方法是什么?

【问题讨论】:

    标签: c# entity-framework mapping


    【解决方案1】:

    坚持

    [Key, Column(Order = 0)]
    CustomerId
    

    CustomerToPropertyMapping 和变化中

    public virtual List<CustomerToPropertyMapping> PropertyIds { get; set; }
    

    [ForeignKey("CustomerId")]
    public virtual List<CustomerToPropertyMapping> PropertyIds { get; set; }
    

    解决了我的问题。

    【讨论】:

      【解决方案2】:

      你应该在客户类中设置主键

      [Table("CUstomerTable")]
      public class Customer
      {
          [Key]
          public int Id { get; set; }
          public virtual List<CustomerToPropertyMapping> PropertyIds { get; set; }
      }   
      
      [Table("CustomerToProperty")]
      public class CustomerToPropertyMapping
      {
          [Key]
          public int PropertyId { get; set; }
          [Column("Customer_ID")]
          public long CustomerId{ get; set; }
            [ForeignKey("CustomerId")]
          public Customer Customer{ get; set; } 
      }
      

      【讨论】:

      • 我的错,我的示例代码中缺少它(刚刚修复它)。其实我已经加了。
      猜你喜欢
      • 2015-08-17
      • 2014-08-21
      • 1970-01-01
      • 2014-04-01
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      • 2017-02-11
      相关资源
      最近更新 更多