可以在没有DbContext实例的情况下构建查询吗?

时间:2013-11-08 18:09:23

标签: c# .net entity-framework dbcontext

我正在使用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实例吗?

2 个答案:

答案 0 :(得分:2)

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);
   }
}

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

答案 1 :(得分:0)

解决方案如下:

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<Func<bool,Brand>> 有人可以证实吗?