Managing Static Data Items in entity

c# entity-framework entity-framework-core

Question

I am having my Domain models as below

public class Employee
{
    public long Id { get; set; }
    public string Name { get; set; }
    public List<Skills> Skills { get; set; }
}

public enum Skills
{
    JAVA,
    DOTNET,
    PYTHON
}

I am trying to model the entity framework models as -

public class Employee
{
    public long Id { get; set; }
    public string Name { get; set; }
    public ICollection<Skills> Skills { get; set; }
}

public class Skills
{
    public long Id { get; set; }
    public string Skill { get; set; }
}

Skills are restricted to one of the few value types. When Entity framework creates the tables, it is creating a Foreign key in Skills table on the EmployeeId PK. Essentially every entry in Employee table will have one or more entry in Skills table. Again, if the Skills is referenced in another entity, another column would be added to store the key referencing it. I am not sure if this is the right way. Is there a way to limit the Skills table to only the static data and have a join table? What would be the best practice for managing the relations with Static data?

1
1
8/9/2018 1:25:39 AM

Accepted Answer

Here you have classical Many-to-Many relationship: one employee can have many skills and a skill can be possessed by many employees. EF Core does not support implicit Many-to-Many relationship as EF6 does, so you need to introduce intermediate entity. Your model will be looking like this:

public class Employee
{
    public long Id { get; set; }
    public string Name { get; set; }
    public ICollection<Skills> Skills { get; set; }
}

public class Skills
{
    public long Id { get; set; }
    public string Skill { get; set; }

    public ICollection<Employee> Employees { get; set; }
}

public class EmployeeSkills
{
    public long SkillsId { get; set; }
    public Skills Skills {get; set;}

    public long EmployeeId { get; set; }
    public Employee Employee {get; set;}
}

In DbContext composite key should be set up for the intermediate entity and Skills data can also be seeded there.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.Entity<EmployeeSkills>(e =>
        {
            e.HasKey(l => new { l.SkillsId, l.EmployeeId });
        });

        modelBuilder.Entity<Skills>(e =>
        {
            e.HasData(new[]
            {
                new Skills() { Id = 1, Skill="JAVA" },
                new Skills() { Id = 2, Skill="DOTNET" },
                new Skills() { Id = 3, Skill="PYTHON" },
            });
        });

        base.OnModelCreating(modelBuilder);
    }
1
8/9/2018 1:21:43 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow