[英]Select Filtered with LINQ and EF
我有一个像这样的类,它是从带有EF的数据库派生的(我的数据库包含该类的所有记录):
public class Products
{
public string color { get; set; }
public string size { get; set; }
public string comment { get; set; }
public string owner { get; set; }
public string buyer { get; set; }
public Nullable<DateTime> After { get; set; }
public Nullable<DateTime> Before { get; set; }
}
现在,在我的Web表单上,用户可以在自由文本框中指定每个属性,并且我想基于这些属性在数据库实体中进行搜索。 用户可以决定填充所有属性,也可以只是其中两个。 如何在EF中创建.select?
任何帮助欢迎!
罗纳德·BR
Db.Products
.Where(p=>string.IsNullOrEmty(colorTexBox.Text) || p.color==colorTexBox.Text)
.Where(p=>check other property...)
.
.
.AsEnumerable()
使用.Contains方法:
private bool IsMatch(string value, string searchCriteria)
{
if(searchCriteria == null || value == null) return true;
return value.ToUpper().Contains(searchCriteria.ToUpper());
}
public Products FindProducts(string color, string size, string comment, string owner, string buyer, datetime? after, datetime? before)
{
using(MyDbContext cont = new MyDbContext())
{
return cont.Products.Where((p) =>
{
return IsMatch(p. color, color) && IsMatch(p.size, size) &&
IsMatch(p.comment, comment) && IsMatch(p.owner, owner) &&
IsMatch(p.buter, buyer); // add your logic for dates here
});
}
}
Products.GetAllProducts().Where(x=>(string.IsNullOrEmpty(txtColor.Text) || x.color ==txtColor.Text) &&
(string.IsNullOrEmpty(txtSize) || x.size == txtSize.Text) &&
--- Same as other fields
).AsEnumerable();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.