我正在尝试编写一个动态搜索I和链接where子句我下面的类和示例代码。
public class Person
{
public int PersonId { get; set; }
//More Fields ..
}
//Link Table
public class PersonAddress
{
public int PersonID { get; set; }
public int AddressID { get; set; }
//More Fields ..
}
public class Address
{
public int AddressId { get; set; }
public int ReferenceDataID { get; set; }
//More Fields ..
}
public class ReferenceData
{
public int ReferenceDataId { get; set; }
public string MyData { get; set; }
//More Fields ..
}
var query = (from p in People.Include("PersonAddresses")
.Include("PersonAddresses.Address")
.Include("PersonAddresses.Address.ReferenceData")
select p);
if (!String.IsNullOrEmpty(searchName))
query = query.Where(q => q.Search.Contains(person.SearchName));
// How can I access the MyData
if (!String.IsNullOrEmpty(searchCountry))
query = query.Where(q => q.Search.Where(a => a. == "Ireland");
感谢。
答案 0 :(得分:1)
如果要过滤相关记录,则在使用包含时无法进行过滤。 Include仅允许加载所有属性。在单个查询中获取过滤导航属性的唯一可能方法是手动查询,投影到非实体或匿名类型:
var query = from p in context.Persons
select new
{
Person = p,
Addresses = p.PersonAddreeses
.Where(pa => pa.Address.Country == "Ireland")
};
如果您想在不过滤加载地址的情况下从爱尔兰获取包含地址的人,则无法使用您定义的查询。期望表达式导致bool
不是另一个查询。试试这个:
query = query.Where(p => p.PersonAddresses
.Any(pa => pa.Address.Country == "Ireland");
我绝对不确定你的例子中Search
是什么。