使用LINQ在EF ​​Core中查询复杂数据类型

时间:2018-08-07 11:06:05

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

我正在使用EF Core和ASP.NET Core API,并且我所定义的实体大致如下:

public class MyUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Circle
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<MyUser> Members { get; set; } = new List<MyUser>();
}

public class Tender
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public TenderVisibility Visibility { get; set; }
    public ICollection<TenderCircle> TenderCircles { get; set; } = new List<TenderCircle>();
}

public enum TenderVisibility
{
    Public,
    Circles,
}

public class TenderCircle
{
    public int TenderId { get; set; }
    [ForeignKey("TenderId")]
    public Tender Tender { get; set; }
    public int CircleId { get; set; }
    [ForeignKey("CircleId")]
    public Circle Circle { get; set; }
}

然后,如果可见性设置为Tenders,那么我想让我的所有Circle都在某个用户是Circles的成员的情况下,所以我有这样的事情: >

    public IEnumerable<Tender> GetTenders(string userId)
    {
        var user = _context.Users.Where(u => u.Id == userId);

        return _context.Tenders
                       .Include("TenderCircles.Circle.Members")
                       .Where(t => t.Visibility == TenderVisibility.Public ||
                             (t.Visibility == TenderVisibility.Circles && t.TenderCircles.Select(tc => tc.Circle.Members).ToList().Contains(user.ToList()))).ToList()
                       .ToList();
    }

但是在我看来,这太复杂了,它实际上不起作用,因为它抛出错误,提示我不允许在第二部分中选择圈子成员并检查是否包含用户。知道如何更有效地实现我想要的吗?

1 个答案:

答案 0 :(得分:1)

您不能在ToList条件下呼叫Where。您可以改用Any

 public IEnumerable<Tender> GetTenders(string userId)
    {
        var user = _context.Users.Where(u => u.Id == userId);

        return _context.Tenders
                       .Include("TenderCircles.Circle.Members")
                       .Where(t => t.Visibility == TenderVisibility.Public ||
                             (t.Visibility == TenderVisibility.Circles && t.TenderCircles.Any(tc => tc.Circle.Members.Any(m=>m.Id == userId)))
                       .ToList();
    }

我无法尝试,因为它的复制有点复杂。但是请让我知道是否有语法错误