【问题标题】:How to use multiple statements in where clause EF 5.0?如何在 where 子句 EF 5.0 中使用多个语句?
【发布时间】:2013-08-04 07:23:25
【问题描述】:

我是 EF 5 的新手。我有一个简单的搜索要求,用户可以根据几个搜索条件搜索给定的实体(比如客户)。用户可以选择使用或不使用标准。搜索条件需要“与”所有条件。所以我写这样的代码

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()"。

还有其他方法可以继续吗?

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    因为我假设来自

    GridView1.DataContext = _customer;
    

    您正在使用 WPF,该错误几乎可以告诉您您需要知道的一切;您不能直接将数据绑定到 EntityFramework 为您创建的DbSet。很可能是简单的修复:

    GridView1.DataContext = _customer.AsEnumerable();
    

    【讨论】:

    • 我正在使用 WinForms 和 DataGridView。
    【解决方案2】:

    编辑:我可能误解了这个问题。但我假设您不能将直接绑定到 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多