Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First Map (Linked) Table?

I'm working with the EF code first approach and want to add a link (map) table. I am working off the below example and get the following error:

System.Data.Entity.Edm.EdmEntityType: : EntityType 'EmployeeDepartmentLink' has no key defined. Define the key for this EntityType.

Problem is I dont want a key on 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 have tried a variety of things like adding the "[Key()]" attribute but it doesn't make sense for it to be used, and which field do I add it to? I am wondering if this sort of table model is even supported?

like image 472
user1882453 Avatar asked Dec 05 '22 12:12

user1882453


1 Answers

You are trying to make a "Many to Many" mapping.

To perform 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");
                });
    }
}
like image 90
lante Avatar answered Feb 01 '23 15:02

lante