【发布时间】:2015-10-27 14:12:52
【问题描述】:
我在 ASP.NET MVC 中有一个方法。我正在做的是更新单列检查表的每一列不为空。如果为 null,则 IsModified 属性更改为 false。我必须为每一列写语句。
我的示例方法 -
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);
我认为这段代码看起来不合逻辑。告诉我更好的方法来做到这一点。 如何通过不编写这么多代码来更新表格的单列?提前致谢。
【问题讨论】:
-
至少您可以将
if语句重写为?:表达式,例如db.Entry(_helplineservice).Property(p => p.contactnumber).IsModified = !string.IsNullOrEmpty(_helplineservice.contactnumber); -
是否要将实体单个属性的更改保存到数据库中?
-
是的@Domysee。我只想更改单个属性。但是当我这样做时,如果其他属性可以为空而不检查 IsModified,则会保存 null。
-
@DavidG 是的,我知道它可以像你说的那样。但是如果我有 50 个属性/列呢?我想避免重复的代码。有没有其他方法可以做到这一点?
-
如何加载实体?通常 EntityFramework 会加载所有属性,因此没有空值(除非它们在数据库中)
标签: c# asp.net asp.net-mvc entity-framework linq