【问题标题】:EF6 CodeFirst ForeignKey attribute mapping not working as expectedEF6 CodeFirst ForeignKey 属性映射未按预期工作
【发布时间】:2016-02-09 08:30:11
【问题描述】:

我有一个多对一的情况,一名员工可以为多个客户提供服务,而每个客户由一名员工提供服务。在 Customer 类中,我使用 ForeignKey 属性将 SupportRep 映射到 EmployeeId,它给了我一个错误。

public class Customer
{
    [Key]
    public int CustomerId { get; set; }
    ...

    public int? SupportRepId { get; set; }

    [ForeignKey("EmployeeId")]
    public virtual Employee SupportRep { get; set; }
}

public class Employee
{
    [Key]
    public int EmployeeId { get; set; }
    ...

    [ForeignKey("SupportRepId")]
    public virtual ICollection<Customer> Customers { get; set; }
}

我得到的错误是:

错误:类型“SqlLiteChinook”的属性“SupportRep”上的 ForeignKeyAttribute。 客户'无效。在 d 上找不到外键名称“EmployeeId” 附加类型“SqlLiteChinook.Customer”。名称值应该是逗号分隔 ted 外键属性名称列表。

但是,如果我在 Customer 类中将 EmployeeId 更改为 SupportRepId,它会起作用。

Customer类中的外键不应该指向Employee类的EmployeeId吗?

请赐教。谢谢。

【问题讨论】:

    标签: c# entity-framework sqlite ef-code-first


    【解决方案1】:

    你把事情搞混了。 Customer 类中的[ForeignKey("EmployeeId")] 必须说明该类的哪个属性是Employee 的外键。该属性不会在 Employee 类中查找外键。

    您的第二个错误是在ICollection&lt;Customer&gt; 上声明了外键。由于您具有一对多关系,因此您的集合不能指向 一个 客户,它与多个客户有关系。因此,您的客户需要拥有员工的外键(每个客户“指向”一名员工),但员工不能包含客户的外键。

    public class Customer
    {
      [Key]
      public int CustomerId { get; set; }
      ...
      public int? SupportRepId { get; set; }
    
      [ForeignKey("SupportRepId")]
      public virtual Employee SupportRep { get; set; }
    }
    
    public class Employee
    {
      [Key]
      public int EmployeeId { get; set; }
      ...
      public virtual ICollection<Customer> Customers { get; set; }
    }
    

    【讨论】:

      【解决方案2】:

      试试这个

      public class Customer
      {
          [Key]
          public int CustomerId { get; set; }
          ...
      
          public int? SupportRepId { get; set; }
      
          [ForeignKey("SupportRepId")]
          public virtual Employee SupportRep { get; set; }
      }
      
      public class Employee
      {
          [Key]
          public int EmployeeId { get; set; }
          ...
      
          public virtual ICollection<Customer> Customers { get; set; }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-19
        • 2020-04-26
        • 2021-09-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多