LINQ查询问题.需要检查是否存在

Pir*_*ada 14 c# linq

我有3个领域:urlName,displayNameactive.这是检查编辑记录.我想在这里做的是UrlName在Db中检查是唯一的,但同时,如果用户已经保存了Url但是已经更改DisplayName,Active那么记录应该更新.

任何人告诉我如何解决这个问题.

public bool NothingExceptUrlNameExists(string urlName, string displayName, bool active)
        {
            return (from p in _db.SubMenus
                    where p.UrlName == urlName && (p.DisplayName != displayName || p.DisplayName == displayName) && (p.Active != active || p.Active == active)
                    select p).Any();
        }
Run Code Online (Sandbox Code Playgroud)

更新记录就像

 TryUpdateModel(existingMenu);
                _menu.Add();
Run Code Online (Sandbox Code Playgroud)

这就是我想要实现的目标

我应该在Query DisplayName和Active中添加其他2个值.假设已经在DB中"联系"UrlName.我正在从下拉列表中加载值,返回UrlName ="About",DisplayName ="About Us",Active = true.现在编辑记录.这是匹配的条件.

1 - UrlName ="关于",DisplayName ="关于测试",活动=真 - >这应该更新.

2 - UrlName ="关于",DisplayName ="关于我们",Active = false - >这应该更新.

3 - UrlName ="关于",DisplayName ="关于测试",活动=假 - >这应该更新.

重要提示:4 - UrlName ="newnotexist",DisplayName ="关于测试",Active = false - > 这应该更新UrlName并在更改时休息.

5 - UrlName ="Contact",DisplayName ="About Test",Active = false - > 这不应更新并生成错误.

我希望你明白我想做什么.

Phi*_*ill 27

基于更新的问题,如果我理解正确,我认为这个解决方案将适合您.

var urlNameExists = _sb.Any(x => x.UrlName == urlName && x.Id != currentEditId);

if (urlNameExists)
     throw Exception("A record with that UrlName already exists");

TryUpdateModel(existingMenu);
_menu.Add();
Run Code Online (Sandbox Code Playgroud)