实体框架4.0代码优先动态查询 [英] Entity Framework 4.0 Code-First Dynamic Query

查看:154
本文介绍了实体框架4.0代码优先动态查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据 KeyValuePair 的列表查询表。使用Model-First方法,我可以执行以下操作:

I would like to query a table based on a list of KeyValuePair. With a Model-First approach, I could do the following:

var context = new DataContext();
var whereClause = new StringBuilder();
var objectParameters = new List<ObjectParameter>();

foreach(KeyValuePair<string, object> pair in queryParameters)
{
    if (whereClause.Length > 0)
        whereClause.Append(" AND ");
    whereClause.Append(string.Format("it.[{0}] = @{0}", pair.Key));
    parameters.Add(new ObjectParameter(pair.Key, pair.Value));
}

var result = context.Nodes.Where(whereClause.ToString(), parameters.ToArray());

现在我使用的是Code-First方法,此方法不再可用。幸运的是,我看到一篇文章(我不记得了),这表明我可以将 DbContext 转换成一个 IObjectContextAdapter 然后调用 CreateQuery ,如下所示:

Now I'm using a Code-First approach and this Where method is not available anymore. Fortunately, I saw an article somewhere (I can't remember anymore) which suggested that I could convert the DbContext to a IObjectContextAdapter then call CreateQuery like this:

var result = ((IObjectContextAdapter)context)
                .ObjectContext.CreateQuery<Node>(whereClause.ToString(), parameters.ToArray());

不幸的是,这会抛出一个错误:

Unfortunately, this throws an error:

'{ColumnName}'无法在当前范围或上下文中解析。确保所有引用的变量都在范围内,所需的模式被加载,并且该命名空间被正确引用。

其中 {ColumnName} whereClause 中指定的列。

任何想法我如何动态查询 DbSet 给出键/值对列表?所有的帮助将不胜感激。

Any ideas how I can dynamically query a DbSet given a list of key/value pairs? All help will be greatly appreciated.

推荐答案

我认为你的第一个问题是,在第一个例子中,你使用 Where 在实体集中,但在第二个示例中,您使用 CreateQuery ,所以您必须传递完整的ESQL查询,而不仅仅是where子句!尝试一下:

I think your very first problem is that in the first example you are using Where on the entity set but in the second example you are using CreateQuery so you must pass full ESQL query and not only where clause! Try something like:

...
.CreateQuery<Node>("SELECT VALUE it FROM ContextName.Nodes AS it WHERE " + yourWhere) 

最有问题的是中的完整实体集名称FROM 部分。我认为它定义为在上下文中公开的上下文类的名称和 DbSet 的名称。另一种方法是创建 ObjectSet

The most problematic is full entity set name in FROM part. I think it is defined as name of the context class and name of the DbSet exposed on the context. Another way to do it is creating ObjectSet:

...
.ObjectContext.CreateObjectSet<Node>().Where(yourWhere)

这篇关于实体框架4.0代码优先动态查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆