这些是示例实体:
public class Person
{
public int Id { get; set; }
public bool IsCool { get; set; }
public List<PersonCommunity> Communities { get; set; }
}
public class Community
{
public int Id { get; set; }
public bool IsPopular { get; set; }
public List<PersonCommunity> People { get; set; }
}
public class PersonCommunity
{
public int PersonId { get; set; }
public Person Person { get; set; }
public int CommunityId { get; set; }
public Community Community { get; set; }
}
这是它们在 ApplicationDbContext 中的配置方式:
public DbSet<Person> People { get; set; }
public DbSet<Community> Communities { get; set; }
public DbSet<PersonCommunity> PersonCommunities { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<PersonCommunity>()
.HasKey(e => new { e.PersonId, e.CommunityId });
modelBuilder.Entity<PersonCommunity>()
.HasOne(e => e.Person)
.WithMany(e => e.Communities)
.HasForeignKey(e => e.PersonId);
modelBuilder.Entity<PersonCommunity>()
.HasOne(e => e.Community)
.WithMany(e => e.People)
.HasForeignKey(e => e.CommunityId);
}
现在我想采取:
- 人
- 通过给定的 ID
但:
- 这个人必须很酷(IsCool = true)
- 此人必须来自至少一个不受欢迎的社区(IsPopular = false)
在所有其他情况下,查询应该返回 null,即使具有给定 ID 的人存在于数据库中。所以查询只是ctx.People.FirstOrDefault(p => p.Id == id)
不在表中。
我想以最优化和最有效的方式实现它,尤其是不将任何不必要的数据加载到程序的内存中。
提示:最初,我必须通过某些标志查询分配到超过 10k 个组的超过 200 万用户,这些组具有多对多关系。而且我不能只使用 SQL。它必须是 EF Core。
我发现很多类似的问题可以部分解决这个问题,或者不满足效率要求,这在这里很关键。