简体   繁体   English

如何在验证方法中区分编辑和创建新项目?

[英]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.

相关问题 如何让我的验证代码在没有绑定的项目上执行? - How can I get my validation code to execute on an item with no binding? 如何在C#中区分托管代码和非托管代码 - How can I distinguish between managed & unmanaged code in C# 如何区分NetStandard 2.0上的Unix和Android? - How can I distinguish between Unix and Android on NetStandard 2.0? 如何让 C# 区分不明确的类名? - How Can I Get C# To Distinguish Between Ambiguous Class Names? 如何区分用户启动和系统启动的进程? - How can I distinguish between user-initiated and system initiated processes? 如何区分选择更改的事件上的鼠标右键和鼠标右键 - how can I distinguish between the right and left mouse click on a selectionchanged event 如何在DataGrid的列中禁用编辑内容 - How can I disable editing content inside a column on my DataGrid 如何将我的新图像的路径作为字符串保存到数据库中,以便在创建新记录后我可以看到我选择的图像? - How to save the path of my new image to the database as a string so that after creating a new record I can see the image that I selected? 创建新帖子时如何在我的博客中添加标签? - How can I add Tags to my blog while creating a new post? 如何在ListView中删除项目? - How I can remove a item in my ListView?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM