基于表名动态获取实体模型?

Getting Entity Model dynamically based on TableName?

我正在将 table 名称传递给函数,我需要动态获取实体的名称并正常使用该实体。

正常的硬编码方式 MyEntity myEntity = new MyEntity();

我试图得到它,但这不起作用

 // 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

                      }

您可以使用 Activator.CreateInstanceDbSet.Create() 来创建实体。然后使用DbSet.Add()将其添加到dbset。

参见下面的示例

object entityObj = dbSet.Create();

//Populate values using reflection / dynamic
//....

dbSet.Add(entityObj);
dbSet.SaveChanges();

希望对您有所帮助。