2

我有两节课

public class Project
{
   [Key]
   public int ID { get; set; }
   public string Name { get; set; }
   public int ManagerID { get; set; }
   public int CoordID { get; set; }
   [ForeignKey("ManagerID")]
   public virtual Employee Manager { get; set; }
   [ForeignKey("CoordID")]
   public virtual Employee Coord { get; set; }

}

public class Employee
{
   [Key]
   public int EmpID { get; set; }
   public string Name { get; set; }
   [InverseProperty("ManagerID")]
   public virtual ICollection<Project> ManagerProjects { get; set; }

  [InverseProperty("CoordID")]
   public virtual ICollection<Project> CoordProjects { get; set; }
}

ManagerID 和 CoordID 映射到 Employee 表的 EmpID 列。我不断收到无效列的错误,因为 EF 无法正确映射。我认为它正在寻找错误的列。

4

2 回答 2

4

我认为InverseProperty用于引用相关的导航属性,而不是外键,例如

public class Employee
{
   [Key]
   public int EmpID { get; set; }
   public int Name { get; set; }
   [InverseProperty("Manager")]
   public virtual ICollection<Project> ManagerProjects { get; set; }

   [InverseProperty("Coord")]
   public virtual ICollection<Project> CoordProjects { get; set; }
}

另外,你的名字是整数而不是字符串有什么原因吗?

于 2013-01-28T21:36:48.223 回答
0

最好的猜测通过OnModelCreating. 通过重命名该列,EF 无法确定要映射的原始对象,因此感到困惑。但是,Fluent API 允许您使用以下内容手动指定地图:

public class MyContext : DbContext
{
  public DbSet<Employee> Employees { get; set; }
  public DbSet<Project> Projects { get; set; }

  protected override OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Project>()
      .HasRequired(x => x.Manager)
      .WithMany(x => x.ManagerProjects)
      .HasForeignKey(x => x.ManagerID);
    modelBuilder.Entity<Project>()
      .HasRequired(x => x.Coord)
      .WithMany(x => x.CoordProjects)
      .HasForeignKey(x => x.CoordID);
  }
}
于 2013-01-28T21:32:33.527 回答