2013-03-11 82 views
2

是的,我想创建一个List<T>,我的T是用户定义的数据类型,即POCO类,例如用户资料。
为什么:我正在使用MvcJqGrid,我想编写一个用于创建Json数据的通用代码,所以在运行时我会知道从哪个类(表)中需要获取数据。我们可以在运行时创建List <用户定义的数据类型>吗?

我的代码

public ActionResult TestGrid() 
{ 
    string spname = Request.Params["storedprocedurename"]; //spname = UserProfile 
    // i get this from the post data of MvcJqGrid i.e. user when create a jqgrid, in 
    // a view defines the table/spname from where data gets loaded in grid. 
    MyEntities _context = new MYEntities();    
    List<UserProfile> userProfiles = _context.UserProfiles.ToList<UserProfile>(); 
    // here some code to create a json data and return 
} 

所以这个用户配置我这里硬编码的,如果我在Request.params 得到RoleMaster(例如),所以我怎样才能做到这一点。

配置细节
的EntityFramework版本= 5.0.0.0数据库第一种方法
MVC 4
MvcJqGrid 1.0.9
的.NET Framework 4.5

+0

你可能会得到一个相关的问题一些更多的信息,其中泛型函数在运行时参数化:http://stackoverflow.com/questions/13 397286/appending-string-to-t-to-produce-a-new-class-name/13397489#13397489 – 2013-03-11 11:55:36

回答

1

如果spName是一个字符串,你可以得到的类型由:

Type genericType = Type.GetType(string.Format("YourNamespace.{0}", spName)); 

然后userProfiles下面将类型的使用代码:

var method = _context.GetType().GetMember("Set") 
       .Cast<MethodInfo>() 
       .Where(x => x.IsGenericMethodDefinition) 
       .FirstOrDefault(); 

var genericMethod = method.MakeGenericMethod(genericType); 
dynamic invokeSet = genericMethod.Invoke(_context, null); 

// this list will contain your List<UserProfile> 
var userProfiles = Enumerable.ToList(invokeSet); 

欲了解更多信息:

  1. Reflection, Linq and DbSet
+0

更新了答案。现在你会得到所需的类型 - 列表 Oliver 2013-03-11 14:04:48

+0

谢谢,这解决了我的问题 – 2013-03-12 05:27:15

0

这将做到这一点:

public ActionResult Index() 
{ 
    string spname = Request.Params["storedprocedurename"]; 
    Type t = typeof(MYEntities) 
     .Assembly 
     .GetType(string.Format("<namespace>.{0}", spname); 
    dynamic instance = Activator.CreateInstance(t); 
    return View(ListData(instance)); 
} 

private List<T> ListData<T>(T instance) 
    where T : class 
{ 
    MYEntities context = new MYEntities(); 
    return context.Set<T>().ToList(); 
} 
相关问题