Entity framework 实体框架代码第一个映射(链接)表?

Entity framework 实体框架代码第一个映射(链接)表?,entity-framework,entity-framework-4,entity-framework-4.1,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()]

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

对于
M:M关系
您必须创建您的join(link)类,如下所示

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

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

}
有关更多信息,请查看

我希望这将对您有所帮助。

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

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

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

检查这正是我要找的@user1882453很高兴听到这有帮助!我知道,在fluentapi中,不创建第三个对象来表示映射表是可能的。
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");
                });
    }
}