AspNet CORE - EF Many To Many to over same table with Join table(AspNet CORE - EF 多对多关系通过联接表实现同一表格的重复)
创始人
2024-09-20 05:00:19
0

首先,我们需要创建一个实体类来表示Join table,该表将用于连接两个具有多对多关系的实体。

public class JoinTable
{
    public int Entity1Id { get; set; }
    public Entity1 Entity1 { get; set; }
    public int Entity2Id { get; set; }
    public Entity2 Entity2 { get; set; }
}

接下来,我们创建两个实体类Entity1和Entity2,它们将具有多对多关系。

public class Entity1
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection JoinTables { get; set; }
}

public class Entity2
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection JoinTables { get; set; }
}

现在,我们需要在DbContext类中配置实体类之间的多对多关系。

public class ApplicationDbContext : DbContext
{
    public DbSet Entity1s { get; set; }
    public DbSet Entity2s { get; set; }
    public DbSet JoinTables { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity()
            .HasKey(jt => new { jt.Entity1Id, jt.Entity2Id });

        modelBuilder.Entity()
            .HasOne(jt => jt.Entity1)
            .WithMany(e1 => e1.JoinTables)
            .HasForeignKey(jt => jt.Entity1Id);

        modelBuilder.Entity()
            .HasOne(jt => jt.Entity2)
            .WithMany(e2 => e2.JoinTables)
            .HasForeignKey(jt => jt.Entity2Id);
    }
}

现在,我们可以使用这些实体类和DbContext来执行多对多关系的操作,例如添加关联关系。

public class Program
{
    static void Main(string[] args)
    {
        using (var context = new ApplicationDbContext())
        {
            var entity1 = new Entity1 { Name = "Entity1" };
            var entity2 = new Entity2 { Name = "Entity2" };

            var joinTable = new JoinTable
            {
                Entity1 = entity1,
                Entity2 = entity2
            };

            context.Entity1s.Add(entity1);
            context.Entity2s.Add(entity2);
            context.JoinTables.Add(joinTable);

            context.SaveChanges();
        }
    }
}

以上示例演示了如何使用AspNet Core和Entity Framework Core实现具有Join table的多对多关系。

相关内容

热门资讯

玩家爆料"佛手在线怎... 玩家爆料"佛手在线怎么调好牌率"开挂(透视)辅助安装(一直是真的有挂)-哔哩哔哩;佛手在线怎么调好牌...
第七分钟带你了解!哥哥打大a有... 第七分钟带你了解!哥哥打大a有辅助吗(透视挂)重磅来袭外挂开挂辅助下载(一贯真的有挂);无需打开直接...
八分钟带你了解!hhpoker... 【亲,hhpoker免费辅助器 这款游戏可以开挂的,确实是有挂的,很多玩家在这款hhpoker免费辅...
科技通报"微信小程序... 科技通报"微信小程序家乡大贰修改器下载"开挂(透视)辅助神器(一贯真的有挂的)-哔哩哔哩;微信小程序...
六分钟带你了解!欢乐茶馆挂有没... >>您好:欢乐茶馆挂有没有确实是有挂的,很多玩家在这款欢乐茶馆挂有没有游戏中打牌都会发现很多用户的牌...
终于知道"上饶中至辅... 终于知道"上饶中至辅助"开挂(透视)辅助工具(一直确实是有挂的)-哔哩哔哩;1、不需要AI权限,帮助...
实测教程"微乐自建房... 实测教程"微乐自建房脚本免费下载"开挂(透视)辅助插件(原来是有挂的)-哔哩哔哩;微乐自建房脚本免费...
6分钟带你了解!爱玩联盟app... 6分钟带你了解!爱玩联盟app辅助(透视挂)记者揭秘外挂开挂辅助插件(果然是有挂的);无需打开直接搜...
一分钟了解"小程序边... 一分钟了解"小程序边锋辅助"开挂(透视)辅助安装(其实是真的有挂的)-哔哩哔哩,小程序边锋辅助是用手...
十分钟带你了解!h5反杀工具(... 十分钟带你了解!h5反杀工具(辅助挂)透视脚本外挂开挂辅助安装(果然确实有挂)《详细加薇136704...