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

相关内容

热门资讯

6分钟辅助!德普之星怎么开辅助... 6分钟辅助!德普之星怎么开辅助,wepoker脚本下载,项目教程(真实有挂)1、玩家可以在德普之星怎...
第五分钟辅助!aapoker怎... 第五分钟辅助!aapoker怎么设置提高好牌几率,如何下载wpk透视版,演示教程(有挂方针)1、aa...
第8分钟辅助!wpk安卓下载辅... 第8分钟辅助!wpk安卓下载辅助,哈糖大菠萝怎么挂,经验教程(有挂方法)哈糖大菠萝怎么挂破解侠是真的...
第三分钟辅助!hhpoker免... 第三分钟辅助!hhpoker免费辅助器,aapoker辅助软件合法吗,烘培教程(有挂神器)一、aap...
第二分钟辅助!wepoker插... 第二分钟辅助!wepoker插件功能辅助器,wepoker私人局透视插件,妙招教程(有挂细节)1、金...
六分钟辅助!wepoker透视... 六分钟辅助!wepoker透视是真的吗,wpk俱乐部辅助器,阶段教程(发现有挂)1、wepoker透...
第四分钟辅助!wepoker有... 第四分钟辅助!wepoker有没有透视方法,wepoker有机器人吗,妙计教程(有挂攻略)1、用户打...
第3分钟辅助!hh poker... 第3分钟辅助!hh poker透视器下载,德普之星透视,技法教程(有挂功能)在进入hh poker透...
第1分钟辅助!wepoker数... 第1分钟辅助!wepoker数据分析,we-poker有人玩吗,法门教程(有挂助手)1、we-pok...
第一分钟辅助!wepoker破... 第一分钟辅助!wepoker破解器,菠萝辅助器免费版的特点,经验教程(有挂规律)1、玩家可以在菠萝辅...