C# - LINQ to EF - 过滤多个子集合

时间:2018-05-15 18:16:27

标签: c# entity-framework linq

简化数据模型:

Customer
--------------
CustomerId (int)
IsActive (bool)
... (a bunch of other fields)
Applications (List<Application>)

Application
--------------
ApplicationId (int)
IsActive (bool)
... (a bunch of other fields)
Member (List<Member>)

Member
--------------
MemberId (int)
IsActive (bool)
... (a bunch of other fields)

给定Customer对象(searchEntity),我希望能够找到DB中的任何其他记录是否具有与给定对象匹配的特定字段。我创建的我认为会返回正确结果的查询是:

foreach (var memberEntity in searchEntity.MEMBER_T.Where(m => m.ISACTIVE == 1).ToList())
{
    bool result = Entities.CUSTOMER_T.Where(c =>
        c.CUSTOMERID != searchEntity.CUSTOMERID && c.ISACTIVE == 1 && c.APPLICATION_T.Where(a =>
            a.ISACTIVE == 1 && a.APPLICATIONSTATUSID == 4 && a.MEMBER_T.Where(m =>
                m.ISACTIVE == 1 && m.FIRSTNAME == memberEntity.FIRSTNAME && m.LASTNAME == memberEntity.LASTNAME
            ).Any()
        ).Any()
    ).Any();
}

如果searchEntity的成员与属于具有ApplicationStatus == 4的应用程序的数据库中的成员的名字和姓氏相匹配,并且该应用程序属于CustomerId不等于searchEntity&的Customer,则返回true #39; s CustomerId。

我遇到的第一个问题是Oracle错误ORA-00904: "Extent1"."CUSTOMERID": invalid identifier。我注意到,如果我修改了我的查询以排除它将执行的a.MEMBER_T.WHERE(...)而没有任何错误 - 除了这是该查询中最关键的部分。

搜索StackOverflow会产生一些建议(LINQ - filter child collectionLINQ - filter collection inside collection)以使用.Select创建新对象并将过滤后的子集合分配给新对象,如下所示:

bool result = Entities.CUSTOMER_T.Where(c =>
    c.CUSTOMERID != searchEntity.CUSTOMERID && c.ISACTIVE == 1
).Select(c => new Database.CUSTOMER_T
{
    CUSTOMERID = c.CUSTOMERID,
    APPLICATION_T = c.APPLICATION_T.Where(a =>
        a.ISACTIVE == 1 && a.APPLICATIONSTATUSID == 4
    ).Select(a => new Database.APPLICATION_T
    {
        APPLICATIONID = a.APPLICATIONID,
        ADDITIONALASSISTANCE_T = a.MEMBER_T.Where(m =>
            m.ISACTIVE == 1
            && m.FIRSTNAME == memberEntity.FIRSTNAME
            && m.LASTNAME == memberEntity.LASTNAME
        )
    }
    ).Where(a => a.ADDITIONALASSISTANCE_T.Any())
}
).Where(c => c.APPLICATION_T.Any()).Any();

导致错误The entity or complex type 'Entities.CUSTOMER_T' cannot be constructed in a LINQ to Entities query。我尝试使用DTO(The entity cannot be constructed in a LINQ to Entities query)解决此问题,但我收到了与上述相同的ORA-00904错误。

我不确定此时还能做些什么。对于要尝试的事情的任何建议将不胜感激。此外,我在这里发布问题是新的,所以如果我错过了某些内容,请告诉我,我会更新我的问题。

0 个答案:

没有答案