3

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?

1
  • I cannot understand how hiding the Collection solves the circular dependency problem. Could you explain a bit? Commented Dec 10, 2017 at 11:48

1 Answer 1

4

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

Comments

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.