我想搜索可能在其名称或产品名称中包含关键字的餐馆。我正在使用LINQ to SQL。 代码是:
数据背景:
protected MyDataContext database;
选项1:
var restaurants = database.tblRestaurants.ByName(keyword).Union(database.tblRestaurants.ByFood(keyword));
ByName 方法的签名:
public static IQueryable<tblRestaurant> ByName(this IQueryable<tblRestaurant> restaurants, string name)
{
var result = from restaurant in restaurants
where restaurant.BusinessName.ToUpper().Contains(name.ToUpper())
select restaurant;
return result;
}
ByFood 方法的签名:
public static IQueryable<tblRestaurant> ByFood(this IQueryable<tblRestaurant> restaurants, string food)
{
var result = from restaurant in restaurants
from product in restaurant.tblProducts
where product.Name.ToUpper().Contains(food.ToUpper())
select restaurant;
return result;
}
工作正常。但我有另一种选择使用左连接。 选项2:
var restaurants = from restaurant in database.tblRestaurants
join product in database.tblProducts
on restaurant.OId equals product.RestaurantOId into products
from p in products.DefaultIfEmpty()
where
p.Name.ToUpper().Contains(keyword.ToUpper()) |
restaurant.BusinessName.ToUpper().Contains(keyword.ToUpper())
select restaurant;
我的问题是,我应该使用哪一个。考虑参数是
在摘要中,如果您同时拥有这两个选项,您会怎么做
答案 0 :(得分:0)
将选项2中的查询更改为如下
from restaurant in restaurants
where restaurant..BusinessName.ToUpper().Contains(keyword.ToUpper())
|| restaurant.tblProducts.FirstOrDefault(p=>p.Name.ToUpper().Contains(keyword.ToUpper()) ) != null
select restaurant;