如何在“包括在EF Core中”中选择特定项目?

时间:2018-09-20 17:44:15

标签: c# asp.net-core entity-framework-core

我有一个看起来像这样的实体:

public class UserOrganization
{
    public string UserId { get; set; }

    [ForeignKey("UserId")]
    public MyUser User { get; set; }

    public int OrganizationId { get; set; }

    [ForeignKey("OrganizationId")]
    public Organization Organization { get; set; }
}

以上实体用于提供MyUserOrganization实体之间的多对多关系。现在,当我想从我的存储库中为用户获取数据时,我也想包含一个组织的数据,并且我有这样的东西:

public IEnumerable<MyUser> GetFullUsers()
{
    return _context.Users
                   .Include(u => u.Location)
                   .Include("UserOrganizations.Organization")
                   // And many other include statements removed for breivty.
                   .ToList();
}

现在,一切正常,我得到了相关数据,但是对于"UserOrganizations.Organization",我得到了很多嵌套数据。我的意思是我的Organization实体包括类型为MyUser的成员,然后它向用户显示,然后再向用户显示组织,依此类推,因为所有内容都被深深地嵌套。因此,基本上我不想获取其他数据,并且我只想从.Include("UserOrganizations.Organization")中选择一些属性。我该如何实现?

请注意,我不想将整个查询都写为select语句,因为为了简便起见,我删除了很多其他内容,因此手动进行映射会很麻烦。我只需要确保.Include("UserOrganizations.Organization")也不会检索嵌套的数据,或者是否可以从Organization中选择要在此处检索的属性?

编辑:

我在OnModelCreating中已有以下内容:

modelBuilder.Entity<UserOrganization>(uo =>
{
    uo.HasKey(k => new { k.UserId, k.OrganizationId });

    uo.HasOne(u => u.User)
      .WithMany(o => o.UserOrganizations)
      .HasForeignKey(k => k.UserId);

    uo.HasOne(o => o.Organization)
      .WithMany(u => u.UserOrganizations)
      .HasForeignKey(k => k.OrganizationId);
});

我的MyUserOrganization实体具有以下属性:

public class MyUser : IdentityUser
{
     // Rest removed for brevity
     public ICollection<UserOrganization> UserOrganizations { get; set; } = new List<UserOrganization>();
}

public class Organization
{
    // Rest removed for brevity
    public ICollection<UserOrganization> UserOrganizations { get; set; } = new List<UserOrganization>();
}

0 个答案:

没有答案