[英]How can I distinguish between editing and creating a new item in my validation method?
I'm trying to ensure that each item in my cms has a unique url. 我试图确保我的cms中的每个项目都有唯一的网址。
The model has been made an IValidatableObject and I am using the validation method below. 该模型已经制成IValidatableObject,并且我正在使用以下验证方法。
The trouble I'm having is discerning whether the item is being created (url must not match any existing items) or edited (url must not match any item other than itself ). 我遇到的麻烦是要确定是正在创建项目(URL不得与任何现有项目匹配)还是已编辑项目(URL不得与除自身以外的任何项目匹配)。
How can I do this... and am I even approaching this the right way? 我该怎么做...我什至正以正确的方式走?
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
DataContext db = new DataContext();
string itemContainingURL = db.CMSPages.Where(c => c.URL == URL).Select(c => c.Title).SingleOrDefault();
if (!string.IsNullOrEmpty(itemContainingURL))
{
yield return new ValidationResult(String.Format("URL should be unique, but it already exists for item: {0}", itemContainingURL), new[] { "URL" });
}
}
Does it matter? 有关系吗? Just test existence of an item of differing ID that shares the URL, and you can cover both cases. 只需测试是否存在共享URL的具有不同ID的项目,就可以解决这两种情况。
Example pseudocode: 伪代码示例:
bool IsUnique()
{
return !repository.Any(x => x.ID != this.ID && x.URL == this.URL);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.