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'
AppUser
? Do you mean Entity Framework Core one to many bidirectional ? Do you wantpublic ICollection<User> Users { get; set; }
?