c# - 将数据添加到实体框架中的动态表
问题描述
我想根据 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
}
解决方案
您可以使用 Set() 方法添加到动态表类型。
var query = context.Set(type);
query.Add(obj);
context.SaveChanges();
唯一的缺点是AddOrUpdate()方法不可用,所以程序运行前需要清空表。该应用程序也很慢,但这是另一篇文章的内容。
推荐阅读
- php - Laravel 7 中对 localhost:3000 的 CORS 支持
- amazon-web-services - 如何将我的 Wordpress 数据库与 lambda 连接?
- openvpn - 在维护时将 VPN 用户路由到另一台服务器
- scala - 如果存在其他外部键,如何获取带有映射键的新列表?
- java - 在 internalStorage 中保存 mp3 文件的问题
- wordpress - 如何将序列化数据保存到 MySQL 的元字段中?
- jquery - 如何使用 jQuery 用表单的文本字段填充表格?
- javascript - Android App软键盘覆盖webview嵌入的网页textarea
- javascript - 显示限制列表并显示更多按钮
- firebase - 响应中带有 google 'Access-Control-Allow-Credentials' 标头的 Flutter Web firebase_auth 登录为 ''(空)