1

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

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

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

4

2 回答 2

0

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

[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; } 
}
于 2012-10-23T13:25:19.850 回答
0

保持

[Key, Column(Order = 0)]
CustomerId

CustomerToPropertyMapping和改变

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

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

解决了我的问题。

于 2012-10-23T15:04:45.850 回答