Entity framework core 实体框架,基于列值的多个一对多关系
在一个实体中,我试图创建与同一子实体的多个一对多关系,其中连接实体中的列的值不同 这里是我正在使用的实体的一个片段Entity framework core 实体框架,基于列值的多个一对多关系,entity-framework-core,Entity Framework Core,在一个实体中,我试图创建与同一子实体的多个一对多关系,其中连接实体中的列的值不同 这里是我正在使用的实体的一个片段 public class Forum { public string Id { get; set; } public ForumType Type { get; set; } // Options are FORUM or GROUP public string Name { get; set; } public string Author { ge
public class Forum
{
public string Id { get; set; }
public ForumType Type { get; set; } // Options are FORUM or GROUP
public string Name { get; set; }
public string Author { get; set; }
public ICollection<Forum> Groups { get; set; } // Child forums with ForumType = GROUP
public ICollection<Forum> Forums { get; set; } // Child forums with ForumType = FORUM
public int Position { get; set; }
public DateTime CreatedAt { get; set; }
}
在建立关系时,我希望论坛
集合的内容使用以下查询:
SELECT * FROM Forums WHERE ParentId = {forumId} AND ForumType = 0
当我加入团队时,我想
SELECT * FROM Forums WHERE ParentId = {forumId} and ForumType = 1
您只需在DatabaseContext
OnModelCreating
方法或实体配置中使用HasMany
:
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions options) : base(options)
{
}
public DbSet<Forum> Forums { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Forum>().HasMany(p => p.Forums);
modelBuilder.Entity<Forum>().HasMany(p => p.Groups);
}
}
您只需在DatabaseContext
OnModelCreating
方法或实体配置中使用HasMany
:
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions options) : base(options)
{
}
public DbSet<Forum> Forums { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Forum>().HasMany(p => p.Forums);
modelBuilder.Entity<Forum>().HasMany(p => p.Groups);
}
}
我担心这并不能解决问题,因为一对多关系不知道我要通过列的值过滤什么。您不需要任何过滤器。插入数据时,您应该只使用正确的集合。例如,当你想添加类型为Group的新论坛时,你应该使用Groups集合。也许我没有正确理解你的要求。我把你的问题读了好几遍,我想你应该使用全局查询过滤器。我已经更新了我的原始问题,希望能让它更清楚。我担心这并不能解决问题,因为一对多关系不知道我想通过列的值过滤什么。你不需要任何过滤器。插入数据时,您应该只使用正确的集合。例如,当你想添加类型为Group的新论坛时,你应该使用Groups集合。也许我没有正确理解你的要求。我把你的问题读了好几遍,我想你应该使用全局查询过滤器。我更新了我原来的问题,希望能让它更清楚。
var forum = new Forum(ForumType.Group)
{
Groups = new List<Forum> { new Forum(ForumType.Group), new Forum(ForumType.Group) },
Forums = new List<Forum> { new Forum(ForumType.Forum), new Forum(ForumType.Forum) }
};
context.Forums.Add(forum);
context.SaveChanges();
var forum = await context.Forums
.Include(c => c.Forums)
.Include(c => c.Groups)
.FirstOrDefaultAsync(x => x.Id == yourId));