使用 Fluent API 对唯一约束进行服务器端验证
Server Side Validation for Unique Constraint using Fluent API
使用 Fluent API 作为 OR/M 并实现了 UNIQUE
的后续专栏,如本 SO post 中所述。
对于服务器端验证,下面的代码工作正常:
[HttpPost]
public ActionResult Save(Company company)
{
try
{
if (company.Id == 0)
_context.Companies.Add(company);
else
{
var companyInDb = _context.Companies.Single(c => c.Id == company.Id);
companyInDb.Name = company.Name;
}
_context.SaveChanges();
return RedirectToAction("Index", "Companies");
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
var error = ex.EntityValidationErrors.First().ValidationErrors.First();
this.ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
return View("CompanyForm");
}
}
How to Validate for Unique values in server side?
尝试了以下代码 catch
完全没有响应
catch (System.Data.SqlClient.SqlException ex)
{
this.ModelState.AddModelError("Duplicate Value", ex.Message);
return View("CompanyForm");
}
你可以试试这个:
using System.Data.Entity.Infrastructure;
//....
catch (DbUpdateException e) when ((e?.InnerException?.InnerException as System.Data.SqlClient.SqlException)?.Number == 2601)
{
this.ModelState.AddModelError("NameOfColumn", "Item with such NameOfColumn already exist");
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
var error = ex.EntityValidationErrors.First().ValidationErrors.First();
this.ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
}
return View("CompanyForm");
使用 Fluent API 作为 OR/M 并实现了 UNIQUE
的后续专栏,如本 SO post 中所述。
对于服务器端验证,下面的代码工作正常:
[HttpPost]
public ActionResult Save(Company company)
{
try
{
if (company.Id == 0)
_context.Companies.Add(company);
else
{
var companyInDb = _context.Companies.Single(c => c.Id == company.Id);
companyInDb.Name = company.Name;
}
_context.SaveChanges();
return RedirectToAction("Index", "Companies");
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
var error = ex.EntityValidationErrors.First().ValidationErrors.First();
this.ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
return View("CompanyForm");
}
}
How to Validate for Unique values in server side?
尝试了以下代码 catch
完全没有响应
catch (System.Data.SqlClient.SqlException ex)
{
this.ModelState.AddModelError("Duplicate Value", ex.Message);
return View("CompanyForm");
}
你可以试试这个:
using System.Data.Entity.Infrastructure;
//....
catch (DbUpdateException e) when ((e?.InnerException?.InnerException as System.Data.SqlClient.SqlException)?.Number == 2601)
{
this.ModelState.AddModelError("NameOfColumn", "Item with such NameOfColumn already exist");
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
var error = ex.EntityValidationErrors.First().ValidationErrors.First();
this.ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
}
return View("CompanyForm");