3

我正在使用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()]」屬性的東西,但它沒有意義,它將被使用,以及我將它添加到哪個字段?我想知道這種表模型是否被支持?

+0

選中此http://stackoverflow.com/questions/5482670/entity-framework-code -first-define-the-key-for-this-entitytype – Sampath

回答

1

對於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

我希望這會幫助你。

+0

正是我在找的東西! – user1882453

+0

@ user1882453很高興聽到它的幫助! – Sampath

13

您正在嘗試製作「多對多」映射。

要執行此,寫這樣的代碼:

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

+1。 EF會自動創建映射表。 –

+1

我知道在流暢的API中可以創建第三個對象來表示映射表。 – Rhyous