[英]Entity Framework and Generic Type Parameter
I have a database with several hundred tables imported from a third source. 我有一个数据库,其中包含从第三个来源导入的几百张表。 Using entity framework, these tables become ObjectSets labeled E_1, E_2, E_3... All of the tables have a common set of columns and can be queried with one function.
使用实体框架,这些表成为标记为E_1,E_2,E_3的对象集。所有表都具有一组公共列,并且可以使用一个函数进行查询。
I have the following code: 我有以下代码:
namespace Foo{
public static class Data{
public static MyEntities dataContext = new MyEntities();
public static void getData<T>(string entityName) where T : class
{
string queryString = "SELECT result FROM ";
queryString += Data.dataContext.DefaultContainerName + "." + entityName;
ObjectQuery<T> myQuery = Data.dataContext.CreateQuery<T>(queryString, null);
// do stuff
}
public static void test(){
string entityName = "E_1";
Data.getData<E_1>(entityName);
}
}
In test(), I pass the string "E_1" to the function getData(), and I also insert type class Foo.E_1 into getData<> as the generic type parameter. 在test()中,我将字符串“ E_1”传递给函数getData(),还将类型类Foo.E_1插入到getData <>中作为通用类型参数。
In reality, E_1 isn't known until run time. 实际上,直到运行时才知道E_1。 At run time, I create the entityName string, but how can I then convert this string into the generic parameter type needed for getData<>?
在运行时,我创建了entityName字符串,但是如何将该字符串转换为getData <>所需的通用参数类型?
Thanks. 谢谢。
In reality, E_1 isn't known until run time
实际上,直到运行时才知道E_1
Anjd in reality that is: 实际上,Anjd是:
Simple like that. 这样简单。
All of the tables have a common set of columns
所有表都有一组通用的列
So you can make one class (eg MyImportType) to capture the results of your query, and use ExecuteStoreQuery
in stead of ObjectQuery
因此,您可以使一个类(例如MyImportType)捕获您的查询结果,并使用
ExecuteStoreQuery
代替ObjectQuery
var data = Data.dataContext.ExecuteStoreQuery<MyImportType>(queryString);
And getData does not need a generic type parameter. 而且getData不需要泛型类型参数。
As aside: I agree with TomTom that the db design is very bad. 顺便说一句:我同意TomTom的数据库设计非常糟糕。 If you can, at least merge the tables with identical columns into one table.
如果可以,请至少将具有相同列的表合并到一个表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.