entity-framework - Entity Framework 代码第一映射(链接)表?

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

我正在使用 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()]”属性,但使用它没有意义,我将它添加到哪个字段?我想知道是否甚至支持这种表格模型?

最佳答案

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

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

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");
                });
    }
}

关于entity-framework - Entity Framework 代码第一映射(链接)表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14439840/

相关文章:

c# - Entity Framework - 数据绑定(bind)自定义字段错误(未找到属性)

entity-framework-4 - 将 EF4 DbContext 与域服务一起使用

entity-framework - EF 4.1, 继承与共享主键关联 => 指定表达式的 ResultType 不兼容

.net - Entity Framework 外键到非主键字段

c# - 在 JSON 中解析 LINQ 答案

c# - EF 更新不更新 GridView

c# - 自定义setter添加多对多关系.net core

c# - 在 Entity Framework 上运行原始 SQL 查询的 KeyValuePair

entity-framework-4 - 我可以使用Entity Framework 4 CTP5访问TPH映射中的鉴别符值吗

c# - 模型创建期间的 Entity Framework NullReferenceException