4

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?

1

2 Answers 2

15

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");
                });
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I knew it would be possible in the fluent API without creating a third object to represent the mapping table.
2

For M:M relationship you have to create your join (link) class is as 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

I hope this will help to you.

1 Comment

Just what I was looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.