use*_*453 3 entity-framework entity-framework-4 entity-framework-4.1
我正在使用EF代码第一种方法,并希望添加一个链接(map)表.我正在处理以下示例并获得以下错误:
System.Data.Entity.Edm.EdmEntityType: : EntityType 'EmployeeDepartmentLink' has no key defined. Define the key for this EntityType.
Run Code Online (Sandbox Code Playgroud)
问题是我不想在这张桌子上放一把钥匙它只是将两张桌子映射在一起:
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;
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了各种各样的事情,比如添加"[Key()]"属性,但是它没有意义使用它,我将它添加到哪个字段?我想知道是否支持这种表模型?
lan*_*nte 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>();
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在你的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");
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8372 次 |
| 最近记录: |