First map table (Entity Framework Code)?
I am working with the first EF code approach and want to add a link (maps) table. I am working on the below example and am getting the following error:
System.Data.Entity.Edm.EdmEntityType: : EntityType 'EmployeeDepartmentLink' has no key defined. Define the key for this EntityType.
The problem is I don't want a key in this table, it just maps the two tables together:
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;
}
I've tried various things like adding the "[Key ()]" attribute, but it doesn't make sense to use it, and in which field am I adding it? I am wondering if this table model is supported?
source to share
For M:M relationship
you need to create your own connection class (link) as shown below.
public class EmployeeDepartmentLink
{
[Key, Column(Order = 0)]
public int EmployeeID;
[Key, Column(Order = 1)]
public int DepartmentID;
}
For more information check Create code first, many to many
Hope this helps you.
source to share
You are trying to make a Many to Many display.
To do this, write this code:
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>();
}
}
then in your 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");
});
}
}
source to share