Search code examples
sqllinqasp.net-coreentity-framework-coreef-code-first

In entity framework core, how we can set relationship for a table, when two fields is mapping to primary key of the another table


In entity framework core, how we can set relationship for a table, when two fields is mapping to primary key of the another table. For example I have two table namely Users & CashBox.

Users Table

Field Value
UserId int
UserName string

CashBox Table

Field Value
CashBoxId int
ActivatedBy int
DeactivatedBy int

In this case, activatedby & deactivatedby has to be linked with user table. Need to know who activated cashbox & who deactivated cashbox.

Using EF core code first approach.


Solution

  • With the following entity models -

    public class User
    {
        [Key]
        public int UserId { get; set; }
        public string UserName { get; set; }
    }
    
    public class CashBox
    {
        [Key]
        public int CashBoxId { get; set; }
        public int ActivatedBy { get; set; }
        public int DeactivatedBy { get; set; }
    
        public User ActivatedUser { get; set; }
        public User DeactivatedUser { get; set; }
    }
    

    you can configure the relationship as -

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<CashBox>(e =>
        {
            e.HasOne(p => p.ActivatedUser)
            .WithMany()
            .HasForeignKey(p => p.ActivatedBy);
    
            e.HasOne(p => p.DeactivatedUser)
            .WithMany()
            .HasForeignKey(p => p.DeactivatedBy);
        });
    }