gpt4 book ai didi

c# - DBContext 自定义验证

转载 作者:太空宇宙 更新时间:2023-11-03 16:17:47 25 4
gpt4 key购买 nike

对 DBContext 比较陌生,尝试在 DBContext 中编写自定义验证而不实现IValidatableObject 接口(interface)或ValidateEntity 覆盖。

例如对于具有以下内容的部门实体:姓名过境#盲点

这是保存逻辑的片段:

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。

最佳答案

我建议将所有通用逻辑提取到您正在保存的同一类中的验证方法中(即返回 bool 值的方法:如果通过则为 True,如果通过则为 False如果没有。您也可以将错误消息用作 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;
}

然后,这样做将允许您在保存方法的开头调用此验证方法,然后仅在它通过后才执行添加/附加。

关于c# - DBContext 自定义验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15208610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com