如何防止在使用实体框架更新单列时将其他列值更改为表
本文关键字:其他 单列时 何防止 实体 更新 框架 | 更新日期: 2023-09-27 18:19:23
这里我有一个方法在ASP。净MVC。我所做的是更新单列检查表的每一列不为空。如果为空,则IsModified属性更改为false。我必须为每一列写语句。
My Sample Method -
public int ServicesEdit(helplineservice _helplineservice)
{
int result = 0;
try
{
db.Entry(_helplineservice).State = EntityState.Modified;
if (string.IsNullOrEmpty(_helplineservice.description))
{
db.Entry(_helplineservice).Property(p => p.description).IsModified = false;
}
else
{
db.Entry(_helplineservice).Property(p => p.description).IsModified = true;
}
if (string.IsNullOrEmpty(_helplineservice.title))
{
db.Entry(_helplineservice).Property(p => p.title).IsModified = false;
}
else
{
db.Entry(_helplineservice).Property(p => p.title).IsModified = true;
}
if (string.IsNullOrEmpty(_helplineservice.contactnumber))
{
db.Entry(_helplineservice).Property(p => p.contactnumber).IsModified = false;
}
else
{
db.Entry(_helplineservice).Property(p => p.contactnumber).IsModified = true;
}
//if (string.IsNullOrEmpty(_helplineservice.active.ToString()))
//{
// db.Entry(_helplineservice).Property(p => p.active).IsModified = false;
//}
//else
//{
// db.Entry(_helplineservice).Property(p => p.active).IsModified = true;
//}
db.SaveChanges();
result = 1;
}
catch (Exception ex)
{
result = 0;
}
return result;
}
调用上述方法-
helplineservice _helplineservice = new helplineservice();
_helplineservice.helplineid =sectionid;
_helplineservice.allowedtoapp = allow;
result = _ftwCommonMethods.ServicesEdit(_helplineservice);
我认为这段代码看起来不符合逻辑。告诉我更好的方法。如何通过不写这么多代码来更新表的单列? Thanks in Advance.
你可以通过先加载你想要更新的实体来避免所有的检查。
var context = new DbContext();
// Load entity via whatever Id parameter you have.
var entityToUpdate = context.Set<Type>().FirstOrDefault(x => x.Id == idToUpdate);
if(entityToUpdate != null)
{
entityToUpdate.Value1 = newValue1;
entityToUpdate.Value2 = newValue2;
context.SaveChanges();
}
只有Value1和Value2会被更新。所有其他现有值保持不变。
在您的例子中,您正在做的是创建一个新的空实体,然后将其Key设置为数据库中已经存在的东西。当您将该实体附加到上下文时,EF别无选择,只能假设该实体中的所有值都是新更新的值。