不同模式中两个表之间的关系映射,使用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" 一列将成为外键。

相关内容

热门资讯

透视中牌率!wepoker黑侠... 透视中牌率!wepoker黑侠辅助器,sohoo开挂辅助(透视)最初是有挂(安装教程)1、让任何用户...
透视辅助!拱趴大菠萝有什么挂,... 透视辅助!拱趴大菠萝有什么挂,pokemmo手机版修改器,好像有挂(教你攻略);1、首先打开拱趴大菠...
透视智能ai!hhpoker透... 透视智能ai!hhpoker透视脚本视频,德普之星私人局辅助免费(透视)都是是真的有挂(攻略教程);...
透视软件!悦扑克脚本,红龙po... 透视软件!悦扑克脚本,红龙poker辅助平台,一贯是有挂(科技教程);1、用户打开应用后不用登录就可...
透视免费!hhpkoer辅助器... 透视免费!hhpkoer辅助器,wepokerplus外挂(透视)先前有挂(大神讲解)进入游戏-大厅...
透视透视!pokemmo辅助器... 透视透视!pokemmo辅助器脚本下载,福建大菠萝万能辅助器,总是存在有挂(软件教程);一、福建大菠...
透视辅助!wepoker透视版... 透视辅助!wepoker透视版下载,hh poker透视器下载(透视)素来有挂(wpk教程)1、完成...
透视软件!大菠萝辅助器,拱趴大... 透视软件!大菠萝辅助器,拱趴大菠萝挂,都是是真的有挂(科技教程)1、大菠萝辅助器系统规律教程、大菠萝...
透视挂透视!wepoker私局... 透视挂透视!wepoker私局辅助,wepoker怎么设置盖牌(透视)原本存在有挂(新2025版)所...
透视系统!大菠萝789辅助器下... 透视系统!大菠萝789辅助器下载,wepoker透视有吗,本来有挂(新版2025教程)1、下载好大菠...