首页 > 解决方案 > 将数据添加到实体框架中的动态表

问题描述

我想根据 Excel 输入文件更新数据库。该文件的工作表名称对应于 db.xml 中的表名称。每个 db 表包含不同的列,但与 Excel 列的顺序相对应。有没有办法动态选择要添加新实体的表?

到目前为止我动态创建实体的代码(未经测试,所以我希望):

int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;                           
for (int r = 7; r < rowCount; r++)
{
    var obj = Activator.CreateInstance(Type.GetType("DataGrabber." + xlWorksheet.Name.Remove(xlWorksheet.Name.Length - 1)));
    Type type = obj.GetType();
    IList<PropertyInfo> properties = new List<PropertyInfo>(type.GetProperties());
    int c = 1;

    foreach (PropertyInfo property in properties)
    {
        try
        {
            property.SetValue(obj, (int)xlRange.Cells[r, c].Value2());
        } catch
        {
            property.SetValue(obj, (decimal)xlRange.Cells[r, c].Value2());
        }
        c++;
    }
    context.[dynamic table name].AddOrUpdate(obj); ///// This is my DbContext, how to select the right table based on the type of ob              
}

标签: c#excelentity-framework

解决方案


您可以使用 Set() 方法添加到动态表类型。

var query = context.Set(type);
query.Add(obj);
context.SaveChanges();

唯一的缺点是AddOrUpdate()方法不可用,所以程序运行前需要清空表。该应用程序也很慢,但这是另一篇文章的内容。


推荐阅读