Search code examples
c#entity-framework-core

C# & EF Core : multiple relationships between two tables


There is a first model containing a user

public class User_Profiles
{
    public int id { get; set; }
    public string Name { get; set; }
    public List<order>? orders { get; set; }
}

There is a second model containing an order class:

public class order
{
    public int id { get; set; }
    public int Сreated_UserID { get; set; }
    public User_Profiles Сreated_User { get; set; }
    public int ExecudedUserID { get; set; }
    public User_Profiles ExecudedUser { get; set; }
}

Next I wrote in the context class what is connected

modelBuilder.Entity<order>()
     .HasOne(ps => ps.Сreated_User)
     .WithMany()
     .HasForeignKey(ps => ps.Сreated_UserID)
     .OnDelete(DeleteBehavior.Restrict);

modelBuilder.Entity<order>()
     .HasOne(ps => ps.ExecudedUser)
     .WithMany()
     .HasForeignKey(ps => ps.ExecudedUserID)
     .OnDelete(DeleteBehavior.Restrict);

The connections are established, everything works, but if you look at the database table, a user_profileid column is created.

How to establish such connections correctly and how to avoid creating an unnecessary column?


Solution

  • Solution: Changed the User_Profiles model to the state:

    public class UserProfile
    {
        public int id { get; set; }
        public string Name { get; set; }
        public List<Order>? CreatedLink { get; set; }
        public List<Order>? ExecutedLink {get; set;}
    }
    

    Next I changed the model order:

    public class Order
    {
        public int id { get; set; }
        public int СreatedUserID { get; set; }
        public UserProfile СreatedUser { get; set; }
        public int ExecudedUserID { get; set; }
        public UserProfile ExecudedUser { get; set; }
    }
    

    Made changes to the context class

    modelBuilder.Entity<order>()
         .HasOne(ps => ps.СreatedUser)
         .WithMany(ps=>psCreatedLink)
         .HasForeignKey(ps => ps.СreatedUserID)
         .OnDelete(DeleteBehavior.Restrict);
    
    modelBuilder.Entity<order>()
         .HasOne(ps => ps.ExecudedUser)
         .WithMany(ps=>ps.ExecutedLink)
         .HasForeignKey(ps => ps.ExecudedUserID)
         .OnDelete(DeleteBehavior.Restrict);
    

    And as a result, the field disappeared, disappeared, the connection works and it’s probably more correct this way when the navigation properties are separated