简体   繁体   English

实体框架分配多个外键 - 代码优先方法

[英]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 ).我有两个表,一个存在于数据库中(表Market ),我必须创建一个新表( MarketBranch )。

Table Market :餐桌Market

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

Table MarketBranch :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表中的值必须是市场表中存在的市场 id,所以我不确定如何在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)我的意思是,例如我有 3 个市场(意大利的 id 为 1,德国的 id 为 2,法国的 id 为 3)

在此处输入图像描述

I found the way to solve it, I just have to write, in MarketBranch:我找到了解决它的方法,我只需要在 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:然后,在 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更新数据库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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