【问题标题】:Can we create List<user defined datatype> at runtime?我们可以在运行时创建 List<user defined datatype> 吗?
【发布时间】:2013-02-26 14:07:57
【问题描述】:

是的,我想创建一个List&lt;T&gt;,而我的 T 是用户定义的数据类型,即 POCO 类,例如UserProfile.
为什么:我正在使用MvcJqGrid,我想编写一个通用代码来创建 Json 数据,所以在运行时我会知道我需要从哪个类(表)中获取数据。

我的代码

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 
}

所以我在这里硬编码了这个 UserProfile,如果我在 Request.params 中得到 RoleMaster(例如)怎么办 那么我该如何实现呢。

配置详情
entityFramework Version=5.0.0.0 数据库优先方法
mvc 4
MvcJqGrid 1.0.9
.net 框架 4.5

【问题讨论】:

标签: entity-framework list generics asp.net-mvc-4 mvcjqgrid


【解决方案1】:

这样就可以了:

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();
}

【讨论】:

    【解决方案2】:

    如果 spName 是字符串,可以通过以下方式获取类型:

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

    那么下面的userProfiles 将是List&lt;UserProfile&gt; 类型,使用代码:

    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

    【讨论】:

    • 更新了答案。现在您将获得所需的类型 - List
    猜你喜欢
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 2013-09-14
    • 2017-07-05
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多