Search code examples
foreign-keysentity-framework-migrationscode-first

Entity Framework assign multiple foreign key - code first approach


I don't know how to add two foreign key in the following scenario:

I have two tables, one exists in the database yet (table Market), and I have to create a new table (MarketBranch).

Table Market:

public class Market
{
    public Int16 MarketId { get; set; }
    public string MarketName { get; set; }        
}

Table MarketBranch:

public partial class MarketBranch : BaseModelSingleUserNullable
{
    public Int16 HoldingMarketId { get; set; }
    public Int16 BranchMarketId { get; set; }
}

Values in table must necessarily be the market ids present in the Market table, so I am not sure how to assign foreign keys before doing add-migration

What I mean is that for example I have 3 Markets (Italy with id 1, Germany with id 2 and France with id 3)

enter image description here


Solution

  • I found the way to solve it, I just have to write, in MarketBranch:

    public partial class MarketBranch : BaseModelSingleUserNullable
    {       
    
    public Int16 HoldingMarketId {get;set;}
    public Int16 BranchMarketId {get;set;}
    
    
        public virtual Market  HoldingMarket { get; set; }
    
        public virtual Market BranchMarket{ get; set; }      
    }
    

    Then, in DbContext:

    public virtual DbSet<MarketBranch> MarketBranches { get; set; }
    
    modelBuilder.Entity<MarketBranch>(entity => entity.HasNoKey());
    modelBuilder.Entity<MarketBranch>().HasQueryFilter(p => !p.Deleted);
    

    And last:

    • Add-Migration MarketBranchTable
    • Update-Database