我有一个 ViewModel 和 Repository 正在被 Controller Action for Create 使用
存储库
BackendEntities entity = new BackendEntities();
public void AddCountry(CountriesViewModel countryModel)
{
COUNTRIES2 newCountry = new COUNTRIES2()
{
COUNTRY_ID = countryModel.COUNTRY_ID,
COUNTRY_CODE = countryModel.COUNTRY_CODE,
COUNTRY_NAME = countryModel.COUNTRY_NAME,
ACTION_STATUS = countryModel.ACTION_STATUS,
CREATED_BY = countryModel.CREATED_BY,
CREATED_DATE = countryModel.CREATED_DATE
};
entity.COUNTRIES.Add(newCountry);
entity.SaveChanges();
}
然后,我从用于创建的控制器操作中调用存储库。控制器
public ActionResult Create(FormCollection collection, CountriesViewModel countries)
{
CountriesRepository countryRepo = new CountriesRepository();
if (ModelState.IsValid)
{
try
{
// TODO: Add update logic here
countryRepo.AddCountry(countries);
//countryRepo.
var notif = new UINotificationViewModel()
{
notif_message = "Record saved successfully",
notif_type = NotificationType.SUCCESS,
};
TempData["notif"] = notif;
return RedirectToAction("Index");
}
catch (Exception e)
{
this.AddNotification("Country cannot be added.<br/> Kindly verify the data.", NotificationType.ERROR);
}
}
return View(countries);
}
请如何使用 ACTION_STATUS 不等于 2 的条件验证重复的 COUNTRY_NAME
我不想从模型或视图中执行此操作,而是在控制器或存储库中执行此操作。可能将它放在控制器中的countryRepo.AddCountry(countries)之前。
在您的国家/地区存储库中创建方法
public bool IsNameExist(string name, int id)
{
var result =entity.COUNTRIES.Any(c => c.COUNTRY_NAME == name && c.ACTION_STATUS != 2 && && c.COUNTRY_ID != id);
return result;
}
然后在你的控制器中
public ActionResult Create(FormCollection collection, CountriesViewModel countries)
{
.......
if (countryRepo.IsNameExist(countries.COUNTRY_NAME, countries.COUNTRY_ID))
{
ModelState.AddModelError("COUNTRY_NAME", "COUNTRY NAME already exist.");
}
........
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句