DBContextは比較的新しく、 IValidatableObjectインターフェイスまたはValidateEntityオーバーライドを実装せずにDBContextでカスタム検証を書き込もうとしています。
例:次のような部門エンティティの場合:Name 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をコーディングするためのより良い方法。