Search code examples
c#entity-framework.net-assemblysystem.reflection

Getting Entity Model dynamically based on TableName?


I am passing a table name to a function and I need to get the name of the entity dynamically and use that entity as normal.

Normal hard coded way MyEntity myEntity = new MyEntity();

i tried to get it but this doesnt work

 // Get the Assembly here as the entites exist in another project within the solution

  //Now that we have the assembly, search through it to get the correct entity based on the tablename string
 var assembly = AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.Contains("NAMESPACE")).FirstOrDefault();

                 var type = assembly.GetTypes()
                    .FirstOrDefault(t => t.Name == tableName);

                    if (type != null)
                    {
                        System.Data.Entity.DbSet myDbSet = context.Set(type);

                       myDbSet myEntity = new ??? <-- I need to create an instance of the entity here

                      }

Solution

  • You can either use Activator.CreateInstance or DbSet.Create() to create entity. Then use DbSet.Add() to add it to dbset.

    See sample below

    object entityObj = dbSet.Create();
    
    //Populate values using reflection / dynamic
    //....
    
    dbSet.Add(entityObj);
    dbSet.SaveChanges();
    

    Hope this helps.