不同模式中两个表之间的关系映射,使用CodeFirst。
创始人
2025-01-09 12:00:27
0
  1. 在 DbContext 中分别声明两个 DbSet,对应不同模式中的两个表:
public class MyDbContext : DbContext
{
    public DbSet Table1s { get; set; }
    public DbSet Table2s { get; set; }

    // ...
}
  1. 定义 Table1 和 Table2 的实体类,并为它们添加必要的属性和数据注解。
[Table("Table1", Schema = "Schema1")]
public class Table1
{
    public int Id { get; set; }
    public string Name { get; set; }
    // ...
}

[Table("Table2", Schema = "Schema2")]
public class Table2
{
    public int Id { get; set; }
    public string Description { get; set; }
    public int Table1_Id { get; set; }
    // ...
}
  1. 在 Table2 的实体类中,将 Table1_Id 设置为外键,使用 [ForeignKey] 数据注解指定外键名称和关联表和列的名称:
[Table("Table2", Schema = "Schema2")]
public class Table2
{
    public int Id { get; set; }
    public string Description { get; set; }
    [ForeignKey("Table1Reference")]
    public int Table1_Id { get; set; }
    public virtual Table1 Table1Reference { get; set; }
    // ...
}
  1. 对代码进行迁移,将表格添加到数据库中:
PM> Add-Migration MyMigration
PM> Update-Database
  1. 现在,通过 DbContext 即可在代码中使用两个表的实体类,可以通过查询或修改表1和表2之间的关系:
public void AddTable2ToTable1(int table1Id, Table2 table2)
{
    var table1 = _dbContext.Table1s.Find(table1Id);
    table1.Table2s.Add(table2);
    _dbContext.SaveChanges();
}

此时,在 Schema2 中表2 的数据表中 "Table1_Id" 一列将成为外键。

相关内容

热门资讯

玩家实测!fishpoker透... 玩家实测!fishpoker透视底牌,xpoker透视辅助,分享教程(有挂技巧)1、点击下载安装,微...
揭秘几款!hhpoker有辅助... 1、揭秘几款!hhpoker有辅助吗,wepoker脚本下载,第三方教程(有挂辅助);详细教程。2、...
总算清楚!wepoker祈福有... 总算清楚!wepoker祈福有用吗,wepoker私人局怎么玩,攻略教程(有挂方法);玩家必备必赢加...
记者揭秘!aapoker辅助怎... 记者揭秘!aapoker辅助怎么用,hhpoker是真的还是假的,专业教程(有挂技巧);hhpoke...
盘点一款!epoker透视底牌... 1、盘点一款!epoker透视底牌,大菠萝免费辅助,详细教程(有挂辅助);详细教程。2、大菠萝免费辅...
重大通报!wepoker高级辅... 1、重大通报!wepoker高级辅助,wepoker国外版透视,规律教程(有挂技巧);详细教程。2、...
一秒答解!wepoker究竟有... 一秒答解!wepoker究竟有没有透视,hhpoker脚本下载,介绍教程(有挂透明);建议优先通过w...
每日必备!aapoker公共底... 1、每日必备!aapoker公共底牌,wepoker底牌透视脚本,攻略方法(有挂软件)(UU pok...
今日百科!wepoker破解游... 今日百科!wepoker破解游戏盒子,hardrock透视工具,新2025教程(有挂软件)是由北京得...
1.9分钟了解!wepoker... 自定义wepoker私人局俱乐部辅助系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专...