Use a variable to call a method

拜拜、爱过 提交于 2020-01-04 09:02:53

问题


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

I tried with this way:

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

but it didn't work

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.

and then iterate the collection

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

My variable data is Json with the following structure:

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

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.


回答1:


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



回答2:


I didn't understand very well the idea behind what you are doing, but I guess you want to call a method by a string. You can do this through reflection.

Something like

MethodInfo myFunc = GetType().GetMethod("MyMethodName");
myFunc.Invoke(this, <MyMethodName arguments>);



回答3:


EF core's DbContext has an AddRange<T> method, EF6's not. But of course it's fairly easy to add one, or a couple:

class MyContext : DbContext
{
    ...
    // In case your nameTable1[] arrays are of type object[]
    public void AddRange(params object[] data)
    {
        if (!data.Any()) return;

        var entityType = data[0].GetType();
        Set(entityType).AddRange(data);
    }

    public void AddRange<T>(params T[] data)
        where T : class
    {
        Set<T>().AddRange(data);
    }

    public void AddRange<T>(IEnumerable<T> data)
        where T : class
    {
        Set<T>().AddRange(data);
    }

}


来源:https://stackoverflow.com/questions/57541598/use-a-variable-to-call-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!