如何建立一个动态的FROM子句中的LINQ查询? [英] How to build a dynamic FROM clause for a LINQ query?

查看:121
本文介绍了如何建立一个动态的FROM子句中的LINQ查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标准的LINQ查询:

  VAR列表=从X在SomeDataContext.ViewName
           其中,//其余的where子句
           选择X;
 

我想知道是否有可能建立一个动态的LINQ查询,这样我可以在 SomeDataContext.ViewName 在运行时更改。

我有5个不同的观点,都带有所需要的基本列执行WHERE子句,但对每个其他一些意见不同的列名。

那么,有可能建立了查询,这样我可以在运行时使用不同的背景下,在需要的时候?

例如:

 公共无效的someMethod()
{
    VAR = listA的的GetList(DataContext.ViewA);
    变种数组listB =的GetList(DataContext.ViewB);
    变种listC =的GetList(DataContext.ViewC);
}

公开名单< EntityObject>的GetList(字符串dataContextName)
{
    回报(从x在/ *在这里我想使用dataContextName * /
           其中,//其余的where子句
           选择X).ToList();
}
 

解决方案

您可以用防爆pression树构建动态LINQ查询。这里有一个例子:<一href="http://msdn.microsoft.com/en-us/library/bb882637.aspx">http://msdn.microsoft.com/en-us/library/bb882637.aspx

另一种方法是使用动态LINQ库: <一href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx">http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

这两种方法来说明: <一href="http://www.$c$cproject.com/Articles/231706/Dynamic-query-with-Linq">http://www.$c$cproject.com/Articles/231706/Dynamic-query-with-Linq

从这个例子

predicate Builder使用防爆pression树的方法。

在一般情况下,动态LINQ更容易实现,但前pression树更类型安全的。

I have a standard LINQ query:

var list = from x in SomeDataContext.ViewName
           where //Rest of where clause
           select x;

I would like to know if it is possible to build a dynamic LINQ query so that i can change the SomeDataContext.ViewName at runtime.

I have about 5 different views, all with the basic columns needed to perform the where clause, but with some different column names for each of other views.

So is it possible to build up the query so that i can use the different context at runtime, when needed?

Example:

public void SomeMethod()
{
    var listA = GetList("DataContext.ViewA");
    var listB = GetList("DataContext.ViewB");
    var listC = GetList("DataContext.ViewC");
}

public List<EntityObject> GetList(string dataContextName)
{
    return (from x in /*HERE I WANT TO USE THE dataContextName*/
           where //Rest of where clause
           select x).ToList();
}

解决方案

You can use Expression Trees to build dynamic LINQ queries. Here is an example: http://msdn.microsoft.com/en-us/library/bb882637.aspx

Another approach is to use Dynamic LINQ library: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Both approaches are illustrated here: http://www.codeproject.com/Articles/231706/Dynamic-query-with-Linq

Predicate Builder from this example uses Expression Tree approach.

In general, Dynamic LINQ is easier to implement but Expression Tree is more type-safe.

这篇关于如何建立一个动态的FROM子句中的LINQ查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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