简体   繁体   中英

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)

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM