如何在C#中通过反射更新数据库
How to update db by reflection in c#
我想通过反射更新一个 table 实例
这是我试过的
var type = Assembly.GetExecutingAssembly().GetTypes()
.FirstOrDefault(t => t.Name == TableName);
object instance = Activator.CreateInstance(type);
foreach (var item in dic)
{
PropertyInfo information = type.GetProperties()
.SingleOrDefault(x => x.Name == item.Key);
information.SetValue(instance, item.Value.ToString(), null);
}
var fx = db.Set(instance.GetType());
fx.Add(instance);
result= db.SaveChanges();
它给了我以下异常
InnerException = {"Violation of PRIMARY KEY constraint
'PK_primryKeyName. Cannot insert duplicate key in object 'tableName'.
The duplicate key value is (39).
\r\nThe statement has been terminated."}
它似乎 Entity framework 将其视为插入而不是更新
这就是我们如何处理未附加的东西而无需返回并通过手动获取它select。
var type = Assembly.GetExecutingAssembly().GetTypes()
.FirstOrDefault(t => t.Name == "");
object instance = Activator.CreateInstance(type);
foreach (var item in new Dictionary<string, string>())
{
PropertyInfo information = type.GetProperties()
.SingleOrDefault(x => x.Name == item.Key);
information.SetValue(instance, item.Value.ToString(), null);
}
db.Entry(instance).State = EntityState.Modified;
db.SaveChanges();
我想通过反射更新一个 table 实例
这是我试过的
var type = Assembly.GetExecutingAssembly().GetTypes()
.FirstOrDefault(t => t.Name == TableName);
object instance = Activator.CreateInstance(type);
foreach (var item in dic)
{
PropertyInfo information = type.GetProperties()
.SingleOrDefault(x => x.Name == item.Key);
information.SetValue(instance, item.Value.ToString(), null);
}
var fx = db.Set(instance.GetType());
fx.Add(instance);
result= db.SaveChanges();
它给了我以下异常
InnerException = {"Violation of PRIMARY KEY constraint
'PK_primryKeyName. Cannot insert duplicate key in object 'tableName'.
The duplicate key value is (39).
\r\nThe statement has been terminated."}
它似乎 Entity framework 将其视为插入而不是更新
这就是我们如何处理未附加的东西而无需返回并通过手动获取它select。
var type = Assembly.GetExecutingAssembly().GetTypes()
.FirstOrDefault(t => t.Name == "");
object instance = Activator.CreateInstance(type);
foreach (var item in new Dictionary<string, string>())
{
PropertyInfo information = type.GetProperties()
.SingleOrDefault(x => x.Name == item.Key);
information.SetValue(instance, item.Value.ToString(), null);
}
db.Entry(instance).State = EntityState.Modified;
db.SaveChanges();