我有以下控制器的操作:
public async Task<IActionResult> Create([FromForm]LanguageViewModel viewModel)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
var newLanguage = new Language()
{
Sort = viewModel.Sort,
LangCode = viewModel.Code,
LangName = viewModel.Name
};
await _languageRepository.SaveAsync(newLanguage);
return RedirectToAction("Index");
}
以及以下viewModel
:
public class LanguageViewModel
{
public int Sort { get; set; }
[Required(ErrorMessage = "Language code is required")]
public string Code { get; set; }
[Required(ErrorMessage = "Language name is required")]
public string Name { get; set; }
}
注意,LanguageViewModel
不是我的域(实体框架(对象。对于我数据库中的地图,我有另一个:
public class Language
{
public int LanguageId { get; set; }
public int Sort { get; set; }
public string LangName { get; set; }
public string LangCode { get; set; }
}
因此,我正在使用ASP.NET MVC Core 3.1,我需要检查具有给定代码的Language
是否已经存在。如果它存在,我想展示关于它的验证错误。你可以说我可以像这样解决它:
public async Task<IActionResult> Create([FromForm] LanguageViewModel viewModel)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
var lang = await _languageRepository.All.FirstOrDefaultAsync(x =>
x.LangCode.ToUpper() == viewModel.Code.ToUpper());
if (lang != null)
{
ModelState.TryAddModelError("Code", $"The language with code {viewModel.Code} already exists");
}
if (!ModelState.IsValid)
{
return View(viewModel);
}
var newLanguage = new Language()
{
Sort = viewModel.Sort,
LangCode = viewModel.Code,
LangName = viewModel.Name
};
await _languageRepository.SaveAsync(newLanguage);
return RedirectToAction("Index");
}
好的。它是有效的。但它很丑陋:(也许有更好的解决方案?
也许这是一个更干净的解决方案。
if (_languageRepository.Any(o => o.LangCode.Equals(txnId, StringComparison.InvariantCultureIgnoreCase)))
{
ModelState.TryAddModelError("Code", $"The language with code {viewModel.Code} already exists");
}
最好在EF Core 5:之后尝试一下
https://learn.microsoft.com/en-us/ef/core/modeling/indexes?tabs=data-注释
[Index(nameof(Url), IsUnique = true)]
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}