【问题标题】:Possible to build query without DbContext instance?可以在没有 DbContext 实例的情况下构建查询吗?
【发布时间】:2013-11-09 03:51:09
【问题描述】:

我正在使用 Entity Framework 5。我想构建一个查询(DbQuery?)然后在 DbContext 上执行它。有可能吗?

通常,我会执行这样的查询:

using (var db = new MyDbContext())
{
    var nike = db.Products.Where(p => p.Brand == "Nike").OrderBy(p => p.Name);
    foreach (var product in nike)
    {
        Debug.WriteLine(product.Name);
    }
}

但是我可以在创建 DbContext 之前构造查询,然后在我真正想要检索数据时将查询附加到 DbContext 实例吗?

【问题讨论】:

标签: c# .net entity-framework dbcontext


【解决方案1】:
public IEnumerable<Products> GetProduct(MyDbContext db){
   //query created before-hand
   var nike = db.Products.Where(p => p.Brand == "Nike").OrderBy(p => p.Name);
   return nike;
}

//and then in your method:
using (var db = new MyDbContext()){
   var nike = GetProduct(db); //MyDbContext object attached here.
   foreach(var product in nike){
     Debug.WriteLine(product.Name);
   }
}

也许这就是你想要做的?我不确定。

【讨论】:

【解决方案2】:

解决方案如下:

public Func<bool,Products> Filter()
{
    return i => i.Brand == "Nike"
}
public Func<bool,Products> Filter(string brandName)
{
    return i => i.Brand == brandName;
}


//usage:
db.Products.Where(Filter());
//or
db.Products.Where(Filter("Nike"));

目前我无法测试,但可能你必须使用Expression&lt;Func&lt;bool,Brand&gt;&gt;
有人可以确认吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多