Skip to main content
 首页 » 编程设计

c#之EF 一对一主要关系错误

2024年02月05日10rubylouvre

我在这里查看了其他问题,并查看了我使用 EF 的其他项目,但无法弄清楚为什么在尝试使用 EF 创建带有 View 的 Controller 时出现错误。

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

无法确定类型 PoolCar 和 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; } 
    } 

请您参考如下方法:

我想我以前可能遇到过这个问题并且相信它可能是 EF 中的一个错误。显然,您可以通过在流畅的 API 中配置关系来解决这个问题,请参阅@vinodh 的回答,但如果您坚持使用数据注释,则可以将外键属性放在 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;放; } 来自 Company 模型。

我确实认为这是一个错误,因为我认为当您显式声明外键时,EF 没有理由无法区分哪一侧是依赖项。