1

how to make bidirectional relationship to work in Entity Framework Core?

  • Dotnet 6
  • Ef Core 6.0.13
public class User
{
    public int id { get; set; }
    public string username { get; set; }

    public Department Department{ get; set; }
    public int DepartmentId { get; set; }
}

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

    public User? Manager { get; set; }
    public int? ManagerId { get; set; }
    public ICollection<AppUser> Users { get; set; }
}

DbContext class

public DbSet<User> Users { get; set; }
public DbSet<Department> Departments { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Department>()
                        .HasOne(d => d.Manager)
                        .WithOne(u => u.Department)
                        .HasForeignKey<Department>(d => d.ManagerId);

            modelBuilder.Entity<AppUser>()
                        .HasOne(u => u.Department)
                        .WithMany(d => d.Users)
                        .HasForeignKey(user => user.DepartmentId);


            modelBuilder.SeedDepartments();
        }

Error in Migration

Cannot create a relationship between 'Department.Users' and 'AppUser.Department' because a relationship already exists between 'Department.Manager' and 'AppUser.Department'. Navigations can only participate in a single relationship. If you want to override an existing relationship call 'Ignore' on the navigation 'AppUser.Department' first in 'OnModelCreating'

2

1 Answer 1

1

You have this issue since you're trying to use the same navigation property User.Department in two different relationships. Theoretically you can with this structure have a user that will manage a certain department X while belonging to a different department themselves, for example:

var u = new User{
  id = 1,
  DepartmentId = 1
};
var dept = new Department{
  Id = 2,
  ManagerId = 1,
};

- nothing will stop you at the database level. Hence you need an extra navigation property on User level and corresponding change in your entity configuration:

public class User
{
    public int id { get; set; }
    public string username { get; set; }

    public Department Department{ get; set; }
    public int DepartmentId { get; set; }
    public Department? ManagedDepartment { get; set; }
}

...

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Department>()
                        .HasOne(d => d.Manager)
                        .WithOne(u => u.ManagedDepartment)
                        .HasForeignKey<Department>(d => d.ManagerId);

            modelBuilder.Entity<AppUser>()
                        .HasOne(u => u.Department)
                        .WithMany(d => d.Users)
                        .HasForeignKey(user => user.DepartmentId);


            modelBuilder.SeedDepartments();
        }
4
  • doesnt work : The entity type 'DepartmentManager' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating' Jan 30 at 14:13
  • @reguiegyounes Can you please either update your question with the new code or comment with the changes you made? So far it seems like EF tries to create a join entity on the Manager-Department relationship, which should normally only happen if you try to set up a many-to-many relationship. Jan 30 at 15:42
  • In any case, you can be rest assured that the reason of the issue is identified correctly - the only issue now is finding the right syntax to set it up properly. One other option you have, if your business rules ensure that only the User that belong to a department can be its Manager, is removing the ManagerId completely and creating a new boolean field on User: bool IsManager instead, This will, however, complicate the lookups. Jan 30 at 15:44
  • I did the same as your solution but doesn't work Jan 30 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.