如何创建一个完全动态的LINQ查询? [英] How to create a fully dynamic linq query?
问题描述
我需要建立约30个不同的管理页面,从30个不同的表添加/编辑/删除记录。我能明显花费的时间创造30独特的网页,查询每个表,但我很好奇,如果有一种方法可以简单地创建,查询一个单一的,动态的LINQ查询单,动态页面。这LINQ查询然后返回各个领域和放大器;从指定的表中的记录。
I need to build about 30 different administration pages to add/edit/delete records from 30 different tables. I could obviously spend the time creating 30 unique pages, to query each table, but I'm curious if there's a way to simply create a single, dynamic page that queries a single, dynamic linq query. This linq query then returns all fields & records from a specified table.
我见过类似这样的一个动态的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),但是,仍然需要硬编码表名到查询。我想要做一个选择都与此类似,在这里我通过在表(即产品,订单等)的名称,然后以某种方式查询该表:
I've seen examples of dynamic linq similar to this one (http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx), but that still requires hardcoding the table name into the query. I'd like to do a select all similar to this, where I pass in the name of the table (i.e. "Products", "Orders", etc), and then somehow query that table:
private List<tableName> MyDynamicQuery(string tableName)
{
IEnumerable<tableName> dynamicList;
using (MyEntities db = _conn.GetContext())
{
dynamicList = (from q in db.<tableName>
select q).ToList();
}
return dynamicList;
}
是这样的甚至有可能吗?
Is something like this even possible to do?
感谢
推荐答案
而不是使用表名,你为什么不一个选择传球?它看起来是这样的:
Instead of using table names, why don't you pass in a selector? It would look something like this:
private List<T> GetData<T>(Func<MyEntities, IEnumerable<T>> selector)
{
using (MyEntities db = _conn.GetContext())
{
return selector(db).ToList();
}
}
您会使用它像这样:
var orders = GetData(db => db.Orders);
这篇关于如何创建一个完全动态的LINQ查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!