cuongle
cuongle

Reputation: 75326

Avoid circular dependency in Entity Framework Code First

Assume I have two entities: Nationality and Employee with relationship 1:n.

public class Employee
{
    public int Id { get; set; }
    // More Properties

    public virtual Nationality Nationality { get; set; }
}

public class Nationality
{
    public int Id { get; set; }
    public string Name { get; set; }
}

In order to use Code-First with Entity Framework, I have to add one more property: Employees which I don't expect into Nationality (it creates circular dependency):

public class Nationality
{
    public int Id { get; set; }
    public string Name { get; set; }

    // How to avoid this property
    public virtual List<Employee> Employees { get; set; }
}

So that I can configure the relationship 1: n in Configuration class:

internal class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
    public EmployeeConfiguration()
    {
        HasKey(f => f.Id);

        HasRequired(e => e.Nationality)
          .WithMany(e => e.Employees)
          .Map(c => c.MapKey("NationalityId"));

        ToTable("Employees");
    }
}

Is there any other approach which I can avoid circular dependency and eliminate property Employees out of Nationality class?

Upvotes: 3

Views: 2059

Answers (1)

Eranga
Eranga

Reputation: 32447

Use the WithMany() overload to configure the mapping.

internal class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
    public EmployeeConfiguration()
    {
        HasKey(f => f.Id);

        HasRequired(e => e.Nationality)
          .WithMany()
          .Map(c => c.MapKey("NationalityId"));

        ToTable("Employees");
    }
}

Upvotes: 4

Related Questions