EF一对一主要关系错误

时间:2015-09-04 08:39:14

标签: c# entity-framework

我在这里查看了其他问题,在我的其他项目中使用EF,但无法解决为什么我在尝试使用EF创建带有视图的控制器时出现错误。

我收到的消息告诉我它不理解CompanyPoolCar之间的主要关系,这是一对一的关系。

Unable to determine the principal end of association between the types PoolCar and Company.

公司1< - > 1 PoolCar 1 - < - > * CarAllocation

我已经在依赖表(PoolCar)上分配了外键,但它仍然会抛出相同的错误。

我错过了什么?

[Table("Company")]
    public class Company
    {
        [Key]
        public int companyId { get; set; }
        public string companyName { get; set; }
        // navigation property
        public virtual PoolCar poolCar { get; set; }
    }
    [Table("PoolCar")]
    public class PoolCar
    {
        [Key]
        public int poolCarId { get; set; }
        public int companyId { get; set; }
        [ForeignKey("companyId")]
        public Company company { get; set; }
        public string poolCarName { get; set; }
        // navigation property
        public virtual IList<CarAllocation> carAllocations { get; set; }
    }
    [Table("CarAllocation")]
    public class CarAllocation
    {
        [Key]
        public int carAllocationId { get; set; }
        public int poolCarId { get; set; }
        [ForeignKey("poolCarId")]
        public PoolCar poolCar { get; set; }
        public string allocationName { get; set; }
    }

2 个答案:

答案 0 :(得分:2)

解决方案1 ​​

是外键和关键密钥独立问题。因此,您只需进行流畅的映射,我们就可以非常清楚地理解问题。在流利的Api部分中执行以下操作。

modelBuilder.Entity<Company>()
        .HasOptional(obj => obj.poolCar)
        .WithRequired(obj1 => obj1.company);

答案 1 :(得分:2)

我想我之前可能遇到过这个问题,并且相信它可能是EF中的一个错误。显然你可以通过在流畅的API中配置关系来解决这个问题,请参阅@vinodh answer但是如果你坚持使用数据注释,那么你可以将外键属性放在poolCarId属性上。

[Table("PoolCar")]
public class PoolCar
{
    [Key, ForeignKey("company")]
    public int poolCarId { get; set; }
    public int companyId { get; set; }
    public Company company { get; set; }
    public string poolCarName { get; set; }
    // navigation property
    public virtual IList<CarAllocation> carAllocations { get; set; }
}   

如果你没有在关系的主要方面拥有导航属性,也就是说,如果你从{{public virtual PoolCar poolCar { get; set; }移除Company,那么你的代码也会有用。 1}}模型。

我确实认为这是一个错误,因为我认为当您明确声明外键时,EF无法区分哪一方是依赖方。