我有Contact
个查询,其中包含Communication
子查询,其中包含CommunicationExtension
子查询
static class Program
{
public class Contact
{
public int ContactID { get; set; }
public List<Communication> Communications { get; set; }
public DateTime? DeletionDate { get; set; }
}
public class Communication
{
public int CommuncationID { get; set; }
public List<CommunicationExtension> CommunicationExtensions { get; set; }
public DateTime? DeletionDate { get; set; }
}
public class CommunicationExtension
{
public int CommunicationExtensionID { get; set; }
public int AreaCode { get; set; }
public DateTime? DeletionDate { get; set; }
}
static void Main(string[] args)
{
IQueryable<Contact> q = GenerateData();
IQueryable<Contact> result =
q.Where(c => c.DeletionDate == null &&
c.Communications.Where(co => co.DeletionDate == null &&
co.CommunicationExtensions.Where(ce => ce.DeletionDate == null));
}
private static IQueryable<Contact> GenerateData()
{
return new List<Contact>
{
new Contact
{
ContactID = 1,
DeletionDate = DateTime.Now,
Communications =
new List<Communication>
{
new Communication
{
CommuncationID = 1,
DeletionDate = DateTime.Now,
CommunicationExtensions =
new List<CommunicationExtension>
{
new CommunicationExtension
{
CommunicationExtensionID = 1,
AreaCode = 5,
DeletionDate = null
}
}
},
new Communication
{
CommuncationID = 2,
DeletionDate = null,
CommunicationExtensions =
new List<CommunicationExtension>
{
new CommunicationExtension
{
CommunicationExtensionID = 2,
AreaCode = 55,
DeletionDate = DateTime.Now
}
}
}
}
},
new Contact
{
ContactID = 2,
DeletionDate = null,
Communications =
new List<Communication>
{
new Communication
{
CommuncationID = 1,
DeletionDate = null,
CommunicationExtensions =
new List<CommunicationExtension>
{
new CommunicationExtension
{
CommunicationExtensionID = 3,
AreaCode = 54,
DeletionDate = null
}
}
},
new Communication
{
CommuncationID = 2,
DeletionDate = DateTime.Now,
CommunicationExtensions =
new List<CommunicationExtension>
{
new CommunicationExtension
{
CommunicationExtensionID = 4,
AreaCode = 5565,
DeletionDate = null
}
}
}
}
}
}.AsQueryable();
}
}
当我尝试构建它时,我收到错误:
运营商'&amp;&amp;'不能应用于'bool'和'System.Collections.Generic.IEnumerable'类型的操作数
在线:
IQueryable<Contact> result =
q.Where(c => c.DeletionDate == null &&
c.Communications.Where(co => co.DeletionDate == null &&
co.CommunicationExtensions.Where(ce => ce.DeletionDate == null)));
我需要过滤所有未删除的数据(DeletionDate == null
)。在我的场景中,数据库中有大约200个表,每个表包含可空字段DeletionDate
答案 0 :(得分:1)
问题在于:
c.Communications.Where(co => co.DeletionDate == null &&
co.CommunicationExtensions.Where(ce => ce.DeletionDate == null)
这两行不返回布尔值,因此您的Where
调用不知道如何处理它。您是否希望任何至少有一个未删除Communications
和CommuincationExtensions
的联系人?如果是,请将Where
调用更改为Any
,它应该有效。但请注意,在实际处理您的Contacts
时,您仍需要过滤掉任何已删除的Communications
/ CommunicationExtensions
,因为无论如何,关系都会为您提供相关记录。换句话说,contact.Communications
将返回与Communications
相关的所有Contact
,而comm.CommunicationExtensions
将返回所有CommunicationExtensions
,因此您仍需要过滤掉任何处理过的记录都会被删除。