Entity Framework 4.0 Code-First Dynamic Query

蓝咒 提交于 2019-12-11 12:39:43

问题


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

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}' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly.

Where {ColumnName} is the column specified in the whereClause.

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


回答1:


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) 

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)


来源:https://stackoverflow.com/questions/6297217/entity-framework-4-0-code-first-dynamic-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!