相对较新的DBContext并尝试在DBContext 中编写自定义验证,而实现 IValidatableObject 界面或 ValidateEntity 覆盖。
e.g。 对于具有以下内容的部门实体: 名称 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的更好方法。
答案 0 :(得分:0)
我建议将所有常用逻辑拉出到您正在保存的同一个类中的Validation方法中(即返回bool
值的方法:如果通过则返回true;如果没有则返回False 't。您也可以将错误消息用作out
参数:
private bool ValidateDept(OnlineFormsEntities context, Department dept, out string errorMessage)
{
errorMessage = string.empty;
if (context.Departments.Any(d => d.DepartmentName.ToLower() == dept.DepartmentName.ToLower() && d.ID != dept.ID))
{
errorMessage = "A Department with the given name already exists.";
return false;
}
if (context.Departments.Any(d => d.Transit.ToLower() == dept.Transit.ToLower() && d.ID != dept.ID))
{
errorMessage = "A Department with the given Transit # already exists.";
return false;
}
return true;
}
然后,执行此操作将允许您在保存方法的开头调用此验证方法,然后仅在传递后执行添加/附加。