外键关系的数据注释

时间:2013-01-28 21:07:18

标签: asp.net-mvc-3 entity-framework data-annotations code-first

我有两个班级

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无法正确映射。我认为它正在寻找错误的专栏。

2 个答案:

答案 0 :(得分: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; }
}

另外,您的名字是否为整数而不是字符串?

答案 1 :(得分:0)

最好的猜测是通过OnModelCreating在您的上下文中使用fluent API。通过重命名列,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);
  }
}