开发者

LINQ Chaining Where clauses

I am trying to write a dynamic search I and chain where clauses I have my classes below and sample code.

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 Referen开发者_JS百科ceDataID { 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");

Thanks.


If you want to filter related records it is not possible when using includes. Include allows only loading all properties. The only possible way to get filtered navigation properties in single query is manual query with projection to non entity or anonymous type:

var query = from p in context.Persons
            select new 
            {
                Person = p,
                Addresses = p.PersonAddreeses
                             .Where(pa => pa.Address.Country == "Ireland")
            };

If you want to get person which contains address from Ireland without filtering loaded addresses you cannot use query you defined. Where expects expression resulting in bool not another query. Try this:

query = query.Where(p => p.PersonAddresses
                          .Any(pa => pa.Address.Country == "Ireland");

I'm absolutely not sure what is Search in your example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜