Dynamically select which table to insert data into with entity framework

一笑奈何 提交于 2019-12-13 19:18:32

问题


So I am writing an application which need to select an entity at run time and add through the entity framework save this to a database, I have created the database and a model based off it through the use of an ADO.NET Entity Data model, the objects, which hold the data are chosen baised on the data that is being added at runtime with the use of the reflection class, as follows;

                mytype = Type.GetType(objName);
                myObject = Activator.CreateInstance(mytype);

How can I do something like this to select the entity to use, is can i do something like this:

                db.[MyEntity].Add(myObject);
                db.SaveChanges();

Thanks


回答1:


You can get DbSet by entity type:

var set = db.Set(myObject.GetType());
set.Add(myObject);
db.SaveChanges();



回答2:


You can use generic Set and create a generic method.

public static class MyLibrary
{
    public static void Add<T>(this DbContext db, T obj) where T : class
    {
        db.Set<T>().Add(obj);
    }
}

Usage.

db.Add(myObject);


来源:https://stackoverflow.com/questions/25263469/dynamically-select-which-table-to-insert-data-into-with-entity-framework

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