使用EntityFramework context,我需要使用许多字段进行搜索。
EntityDBContext包括
public class Brand
{
public int BrandID { get; set; }
public string BrandName { get; set; }
public string BrandDesc { get; set; }
public string BrandUrl { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class Product
{
public string Name {get;set;}
public DateTime CreatedDate {get;set;}
public DateTime ExpiryDate {get;set;}
//The product class also contains many fields.(not shown here)
}
var context = new EntityDBContext();
我想使用产品中的字段来搜索品牌。产品的字段仅在运行时是已知的。如何构建使用产品字段搜索品牌的表达式。请看截图。谢谢,Binod
发布于 2014-05-19 15:28:44
首先,我对你问题的这一部分有点不清楚:
the fields of the product are only known at run time.
怎么会这样呢?你能详细说明这一点吗,因为我没有看到一个使用EF的有效实现。您的数据库表(可能是Products
)设置的目的是什么?该类中有哪些属性?
我们需要知道这一点,然后才能给你一个的准确答案。然而,我将给你一个更一般的例子,也许这有助于你理解。
var all_brands_that_sell_shoes = /* But not always ONLY shoes */
myDataContext.Brands
.Where(brand =>
brand.Products.Any(product =>
product.Type == "Shoe")
)
.ToList();
编辑
如果我重新阅读您的问题,您并不是说Product
类的属性直到运行时才知道;而是您事先不知道哪些过滤器需要应用,哪些需要跳过?
第二个答案假设这就是你想要的。再说一次,我不知道你的类的属性,因为你没有发布它们,所以我为了举例而发明了我自己的字段。
首先,创建一个如下所示的对象。这将用于聚合要应用于选定内容的所有筛选器:
public class MySearchCriteria
{
public string ProductName_Contains { get; set; }
public int ProductWeight_LessThan { get; set; }
public int ProductType_Id { get; set; }
}
当您想要过滤列表时,将一个MySearchCriteria
对象传递给该方法:
public List<Brand> GetFilteredList(MySearchCriteria filters)
{
var brands = myDataContext.Brands; //All brands (for now)
if(filters.ProductType_Id > 0)
{
//IF the filter has a value, filter the list accordingly:
brands = brands.Where(brand => brand.Products.Any(product => product.TypeId == filters.ProductType_Id);
}
if(filters.ProductWeight_LessThan > 0)
{
//IF the filter has a value, filter the list accordingly:
brands = brands.Where(brand => brand.Products.Any(product => product.Weight < filters.ProductWeight_LessThan));
}
if(!String.IsNullOrWhiteSpace(filters.ProductName_Contains))
{
//IF the filter has a value, filter the list accordingly:
brands = brands.Where(brand => brand.Products.Any(product => product.Name.Contains(filters.ProductName_Contains)));
}
return brands.ToList();
}
此方法可确保根据您提供的SearchCriteria
过滤列表。
例如,如果您没有使用字段filters.ProductName_Contains
,那么它将是一个空字符串,并且if-evaluation将阻止您基于空字符串进行过滤。最后,您不会应用基于名称的筛选器。
我希望这就是你要找的答案?如果没有,请详细说明,因为我无法理解你想要的是什么。
https://stackoverflow.com/questions/23731906
复制相似问题