【问题标题】:Entity Framework Code First Map (Linked) Table?实体框架代码优先映射(链接)表?
【发布时间】:2013-01-21 13:34:27
【问题描述】:

我正在使用 EF 代码优先方法并希望添加一个链接(地图)表。我正在处理以下示例并收到以下错误:

System.Data.Entity.Edm.EdmEntityType: : EntityType 'EmployeeDepartmentLink' has no key defined. Define the key for this EntityType.

问题是我不想要这个表上的键它只是将两个表映射在一起:

public class Employee
{
    [Key()]
    public int EmployeeID;
    public string Name;
}

public class Department
{
    [Key()]
    public int DepartmentID;
    public string Name;
}

public class EmployeeDepartmentLink
{
    public int EmployeeID;
    public int DepartmentID;
}

我尝试了很多方法,例如添加“[Key()]”属性,但使用它没有意义,我应该将它添加到哪个字段?我想知道是否甚至支持这种表格模型?

【问题讨论】:

标签: entity-framework entity-framework-4 entity-framework-4.1


【解决方案1】:

您正在尝试进行“多对多”映射。

要执行此操作,请编写以下代码:

public class Employee
{
    [Key]
    public int EmployeeId;
    public string Name;
    public List<Department> Departments { get; set; }

    public Employee()
    {
        this.Departments = new List<Department>();
    }
}

public class Department
{
    [Key]
    public int DepartmentId;
    public string Name;

    public List<Employee> Employees { get; set; }

    public Department()
    {
        this.Employees = new List<Employee>();
    }
}

那么,在你的DbContext

public class YourContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Department> Departments { get; set; }

    public YourContext() : base("MyDb")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Department>().
            HasMany(c => c.Employees).
            WithMany(p => p.Departments).
            Map(
                m =>
                {
                    m.MapLeftKey("DepartmentId");
                    m.MapRightKey("EmployeeId");
                    m.ToTable("DepartmentEmployees");
                });
    }
}

【讨论】:

  • 我知道在 fluent API 中可以不用创建第三个对象来表示映射表。
【解决方案2】:

对于M:M relationship,您必须创建您的加入(链接)类,如下所示。

public class EmployeeDepartmentLink
{
    [Key, Column(Order = 0)]
    public int EmployeeID;

    [Key, Column(Order = 1)]
    public int DepartmentID;

}

更多信息请查看Create code first, many to many

希望对你有帮助。

【讨论】:

  • 正是我想要的!
  • @user1882453 很高兴听到它有帮助!
猜你喜欢
  • 2011-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多