是的,我想创建一个List<T>,我的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我在这里硬编码,如果我得到RoleMaster(例如)在Request.params中,我如何实现这一点。
配置细节
entityFramework Version=5.0.0.0数据库第一方法
mvc 4
MvcJqGrid 1.0.9
.net FrameWork 4.5
发布于 2013-03-11 12:06:26
如果spName是字符串,则可以通过以下方法获得类型:
Type genericType = Type.GetType(string.Format("YourNamespace.{0}", spName));然后,下面的userProfiles将是使用代码的List<UserProfile>类型:
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);有关详细信息,请访问:
发布于 2013-03-11 15:01:37
这样可以做到:
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();
}https://stackoverflow.com/questions/15337896
复制相似问题