Use a variable to call a method

asp.net c# entity-framework entity-framework-6

Question

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
2
8/18/2019 9:31:12 AM

Accepted Answer

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();
}
0
8/19/2019 7:19:03 AM

Popular Answer

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

}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow