相对较新的 DBContext 并尝试在 DBContext 中编写自定义验证而不实现IValidatableObject接口或ValidateEntity覆盖。
例如,对于具有以下属性的部门实体:名称 Trasit# BLID
这是保存逻辑的片段:
public static Boolean saveDepartmentDetails(Department dept, out string errorMessage)
{
Boolean isSuccessful = false;
Int32 iRetVal = 0;
errorMessage = string.Empty;
using (OnlineFormsEntities context = new OnlineFormsEntities())
{
if (dept != null)
{
if (dept.DepartmentID > 0)
{
//Todo: I know this is wrong.
if (context.Departments.Where(d => d.DepartmentName.ToLower() == dept.DepartmentName.ToLower() && d.DepartmentID != dept.DepartmentID).Count() > 0)
{
errorMessage = "A Department with the given name already exists.";
return false;
}
if (context.Departments.Where(d => d.Transit.ToLower() == dept.Transit.ToLower() && d.DepartmentID != dept.DepartmentID).Count() > 0)
{
errorMessage = "A Department with the given Transit # already exists.";
return false;
}
context.Departments.Attach(dept);
context.Entry(dept).State = EntityState.Modified;
}
else
{
if (context.Departments.Where(d => d.DepartmentName.ToLower() == dept.DepartmentName.ToLower()).Count() > 0)
{
errorMessage = "A Department with the given name already exists.";
return false;
}
if (context.Departments.Where(d => d.Transit.ToLower() == dept.Transit.ToLower()).Count() > 0)
{
errorMessage = "A Department with the given Transit # already exists.";
return false;
}
context.Departments.Add(dept);
}
try
{
iRetVal = context.SaveChanges();
}
catch (System.Data.OptimisticConcurrencyException opEx)
{
errorMessage = opEx.Message;
((IObjectContextAdapter)context).ObjectContext.Refresh(RefreshMode.ClientWins, dept);
iRetVal = context.SaveChanges();
}
isSuccessful = (iRetVal > 0) ? true : false;
}
}
return isSuccessful;
}
我需要有关更新逻辑的帮助。或者更好的方式来编码这个 SaveDepartmentDetails。