0

i have multiple DbContexts and each context has some DbSets like

public class fooContext : DbContext 
{
    DbSet<fooA> fooA {get,set}
    DbSet<fooB> fooB {get,set}
}

public class barContext : DbContext 
{
    DbSet<barA> barA {get,set}
    DbSet<barB> barB {get,set}
}

and an excel file with multiple excelSheets structered properly for linqtosql to work with (having sheet names as fooA,fooB... ,first row is properties names and remaining rows are data)

i can see that if i have which context has fooA i can use something like this function inside the context

public DbSet Set(string "fooA")
{
  return base.Set(Type.GetType("fooA"));
}

but i don't which context has fooA to add this to

to clarify this ,, normally when you want to add fooARecord to fooA table in fooContext you

fooContext.fooA.Add(fooARecord);

but i only have fooA as string and fooARecord

P.S: cant use linqtosql since oracle and i cant simply import excel to oracle coz too many tables and users need to be able to alter this data before this process

Community
  • 1
  • 1
Modar Na
  • 873
  • 7
  • 18

1 Answers1

2

To check is a fooContext has a DbSet of a specific type only by name, you can do this:

var fooContext = new FooContext(); //the context to check

var dbSets = fooContext.GetType().GetProperties()
                                    .Where(p => p.PropertyType.IsGenericType
                                    && p.PropertyType.GetGenericTypeDefinition()
                                    == typeof(DbSet<>)).ToArray(); //List Dbset<T>

var fooA = "fooA"; //the table to search

var dbSetProp = dbSets.SingleOrDefault(x=> x.PropertyType.GetGenericArguments()[0].Name == fooA);
if(dbSetProp != null) {
    //fooContext has fooA table
    var dbSet = fooContex.Set(dbSetProp.PropertyType.GetGenericArguments()[0]); // or via dbSetProp.GetValue(fooContext) as DbSet
    dbSet.Add(fooARecord);
}
George
  • 777
  • 7
  • 17