简体   繁体   English

如何使用动态类型的IQueryable?

[英]How can I use a dynamically typed IQueryable?

I have an ASP.NET app that uses Kendo Grids to show data. 我有一个使用Kendo Grids显示数据的ASP.NET应用程序。 I am trying to create a way for users to create their own Grids dynamically to show whatever data in the database they want (within limits, of course). 我正在尝试为用户创建一种动态创建自己的网格的方式,以显示他们想要的数据库中的任何数据(当然,在限制范围内)。

My problem arises because I don't know at compile time what table the user will want to query on. 出现我的问题是因为我在编译时不知道用户要在哪个表上查询。 For similar, but static, grids I use the System.Linq.IQueryable object, like so: 对于类似但静态的网格,我使用System.Linq.IQueryable对象,如下所示:

IQueryable<v_InvCountLine> query;
query = from w in dc.v_InvCountLines
            where w.BatchNum == batchNum && w.StoreRoom == storeroom && w.Serialized == 0
            select w;

//where v_InvCountLines is the name of a database table(view).

I want to accomplish a similar thing, but querying a table determined by a string passed in from the user. 我想完成类似的事情,但是要查询由用户传递的字符串确定的表。

From this question I've managed to create such an object, but it is of type object and so it doesn't have access to any of the methods I need to actually do the work. 通过这个问题,我设法创建了一个这样的对象,但是它是object类型的,因此它无法访问我实际进行工作所需的任何方法。

//WOLinq is the name of a database table
Type objectType = Type.GetType("WOLinq");
Type type = typeof(IQueryable<>).MakeGenericType(objectType);
object query = Activator.CreateInstance(type);

Is there a way to cast query down to it's actual type, or some other way to dynamically select a table to query with IQueryable<>? 有没有一种方法可以将query为它的实际类型,或者有其他方法可以动态选择要使用IQueryable <>查询的表?

If we are talking about ASP.NET application with Entity Framework 6 then the best solution will be to use raw SQL queries. 如果我们谈论的是带有Entity Framework 6的ASP.NET应用程序,那么最好的解决方案是使用原始SQL查询。 For example: 例如:

Type entityType = Type.GetType("YourAppNamespace.Models." + typeNameYouGotFromUser);
string tableName = GetTableName(entityType, _dbContext);
var sql = $"SELECT * FROM [{tableName}] WHERE " + SomeOtherConditions;

var list = _dbContext.Database.SqlQuery(entityType, "SELECT * FROM Orders");
foreach (var record in list) { 
    //do whatever you need with record
}

Here GetTableName is the function you can get from this post 这里的GetTableName是您可以从这篇文章中获得的函数

And, of course, you can use our EasyQuery library for such kind of tasks. 而且,当然,您可以将我们的EasyQuery库用于此类任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM