Entity framework 如何在where子句EF 5.0中使用多个语句?
我对EF5很陌生。我有一个简单的搜索要求,用户可以根据几个搜索条件搜索给定的实体(比如说客户)。用户可以选择是否使用标准。搜索条件需要“和”所有条件。所以我写了这样的代码Entity framework 如何在where子句EF 5.0中使用多个语句?,entity-framework,Entity Framework,我对EF5很陌生。我有一个简单的搜索要求,用户可以根据几个搜索条件搜索给定的实体(比如说客户)。用户可以选择是否使用标准。搜索条件需要“和”所有条件。所以我写了这样的代码 IQueryable _customer; _customer = from c in context.Customer where (txtCustomerName.Text.Length == 0 || c.name == txtCu
IQueryable _customer;
_customer = from c in context.Customer
where
(txtCustomerName.Text.Length == 0 || c.name == txtCustomerName.Text)
&& (txtpropcust1.Text.Length == 0 || c.customfield1 == txtpropcust1.Text)
&& (txtpropcust2.Text.Length == 0 || c.customfield2 == txtpropcust2.Text)
&& (txtpropcust3.Text.Length == 0 || c.customfield3 == txtpropcust3.Text)
&& (txtpropcust4.Text.Length == 0 || c.customfield4 == txtpropcust4.Text)
&& (txtpropcust5.Text.Length == 0 || c.customfield5 == txtpropcust5.Text)
select c;
GridView1.DataContext = _customer;
我得到的错误是“不支持直接绑定到存储查询(DbSet、DbQuery、DbSqlQuery)的数据。而是使用数据填充DbSet,例如通过调用DbSet上的Load,然后绑定到本地数据。对于WPF,绑定到DbSet.local。对于WinForms,绑定到DbSet.local.ToBindingList()”
有没有别的方法可以继续呢?因为我是从
GridView1.DataContext = _customer;
当您使用WPF时,错误几乎告诉您所有您需要知道的信息;您不能直接将数据绑定到为您创建的EntityFramework的DbSet
。简单的修复可能是:
GridView1.DataContext = _customer.AsEnumerable();
因为我是从
GridView1.DataContext = _customer;
当您使用WPF时,错误几乎告诉您所有您需要知道的信息;您不能直接将数据绑定到为您创建的EntityFramework的DbSet
。简单的修复可能是:
GridView1.DataContext = _customer.AsEnumerable();
编辑:也许我误解了这个问题。但是我假设您不能将direclty绑定到IQueryable,所以您可能需要.ToList()或.ToEnumerable()。我们的提供者(db2)不喜欢这种语法,因此我的答案是。真正的解决办法由@Tieson T指出
不确定您的确切问题,但通常通过使用if
来实现。如果在很多地方需要,您可以编写一个简单的扩展方法来封装这个逻辑
var query = from d in db.Customers;
if (text1.Length > 0) query = query.Where(x => x.Field == text1)
if (text2.Length > 0) query = query.Where(x => x.Other == text2)
var data = query.ToList(); // etc
编辑:也许我误解了这个问题。但是我假设您不能将direclty绑定到IQueryable,所以您可能需要.ToList()或.ToEnumerable()。我们的提供者(db2)不喜欢这种语法,因此我的答案是。真正的解决办法由@Tieson T指出
不确定您的确切问题,但通常通过使用if
来实现。如果在很多地方需要,您可以编写一个简单的扩展方法来封装这个逻辑
var query = from d in db.Customers;
if (text1.Length > 0) query = query.Where(x => x.Field == text1)
if (text2.Length > 0) query = query.Where(x => x.Other == text2)
var data = query.ToList(); // etc
我正在使用WinForms和DataGridView。我正在使用WinForms和DataGridView。