Wil*_*lem 5 .net c# linq linq-to-entities entity-framework-4.1
我有一个标准的LINQ查询:
var list = from x in SomeDataContext.ViewName
where //Rest of where clause
select x;
Run Code Online (Sandbox Code Playgroud)
我想知道是否可以构建动态LINQ查询,以便我可以SomeDataContext.ViewName在运行时更改.
我有大约5个不同的视图,都具有执行where子句所需的基本列,但每个其他视图都有一些不同的列名.
那么是否可以构建查询以便在需要时可以在运行时使用不同的上下文?
例:
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();
}
Run Code Online (Sandbox Code Playgroud)
您可以使用表达式树来构建动态LINQ查询.这是一个例子:http://msdn.microsoft.com/en-us/library/bb882637.aspx
另一种方法是使用动态LINQ库:http: //weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
这两种方法都在这里说明:http: //www.codeproject.com/Articles/231706/Dynamic-query-with-Linq
此示例中的Predicate Builder使用表达式树方法.
通常,Dynamic LINQ更容易实现,但Expression Tree更加类型安全.
| 归档时间: |
|
| 查看次数: |
2507 次 |
| 最近记录: |