使用变量来调用方法 [英] Use a variable to call a method

查看:125
本文介绍了使用变量来调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Entity Framework来操纵数据库,我想知道是否可以使用变量来调用方法

I'm using Entity framework to manipulate a data base, and I was wondering if I could used a variable to call a method

我尝试过这种方式:

string name = "tableName";
db.[name].AddRange(dates.[name]);

但是没有用

我想调用这种方法,因为我要在不同的表中进行多次插入.并且我想到了使用带有表的所有名称的数组或某些集合.

I want to call a method of this way because I'm going to do multiples inserts in different tables. and I have in mind use an array or some collection with all the names of the tables.

然后遍历集合

public ActionResult MetodoRecibe(Reporte datas)
{
   string name = "tableName";
   db.tableName.AddRange(datos.tableName);
   db.SaveChanges();
   return Json(datas, JsonRequestBehavior.AllowGet);
 }

我的变量数据是具有以下结构的Json:

My variable data is Json with the following structure:

datas{
nameTable1[],
nameTable2[],
nameTable3[],
.
.
.
.
nameTable13
}

我曾经考虑过使用switch case作为最后的手段,但是由于表的数量,我宁愿使用第一个选项.

I had considered using a switch case as a last resort but because of the quantity of tables I would prefer to use the first option.

推荐答案

您将需要使用反射进行此操作. 尝试如下操作:

You will need to use reflection for doing such operation. Try like following:

public ActionResult MetodoRecibe(Reporte datas)
{
  string name = "TableName"; // This has to be exact with EF entity name
  var type = ((IQueryable)efContext.GetType().GetProperty("TableName").GetValue(efContext)).ElementType;
  var dbSet = efContext.Set(type); 
  dbset.AddRange(dates.[name]);
  efContext.SaveChanges();
}

这篇关于使用变量来调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆