繁体   English   中英

在实体框架中将映射表作为实体加载

[英]loading mapping table as an entity in entity framework

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

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类中。

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

您应该在客户类别中设置主键

[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; } 
}

保持

[Key, Column(Order = 0)]
CustomerId

CustomerToPropertyMappingCustomerToPropertyMapping和更改

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

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

解决了我的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM