Appending my query in LINQ to SQL
I'm trying to build my l2s query based on the existence of a parameter. I am able to achieve this for direct properties of my object, but when one of the properties is a many -> many entity, I'm unable to figure it out.
For example, my user table has a name column.
There is also a brand table and a user may have multiple brands as stored in the brand_users table.I want to append to my query a condition that will query only users that have 开发者_如何学JAVAan entry in the brand_users table with a specific brandid.
GetUser(UserSearchParameter searchParam)
{
var query = from u in Users select u;
if(searchParam.Name != null)
query = query.Where(u => u.Name.Contains(searchParam.Status)); // this works!!
if(searchParam.BrandId != null)
query = query.Where??? // this is where I'm stuck
return new List<user>(query);
}
How about:
query = query.Where(u => Brands.Any(brand => brand.UserId == u.UserId &&
brand.BrandId == searchparam.brandId));
It's hard to give more detail without knowing the structure of your brands table though, or how it's represented in LINQ to SQL.
Something like
query = query.Where(u => u.Brand_Users.Any());
Assuming you've mapped the brand_users many->many table in a L2S relationship, with the name as above.
精彩评论