Problem with LINQ query. Check if there is

I have 3 fields: urlName , displayName and active . This is a validation of an edit entry. Here I want to check that urlName is unique in Db, but at the same time, if the user has already saved Url, but changed displayName and active , then the record should be updated.

Someone will tell me how to solve this.

 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(); } 

record update for example

  TryUpdateModel(existingMenu); _menu.Add(); 

This is what I want to achieve.

My other 2 values ​​should be added to Query DisplayName and Active. Suppose that "Contact" UrlName is already in the database. I load the values ​​from the drop-down list that returns UrlName = "About", DisplayName = "About Us", Active = true. Now edit the record. Here is the condition for compliance.

1 - UrlName = "About", DisplayName = "About testing", Active = true β†’ This should be updated.

2 - UrlName = "About", DisplayName = "About Us", Active = false β†’ This should be updated.

3 - UrlName = "", DisplayName = "About testing", Active = false β†’ This should be updated.

Important: 4 - UrlName = "newnotexist", DisplayName = "About testing", Active = false β†’ This should update UrlName and rest if they are changed.

5 - UrlName = "Contact", DisplayName = "About Test", Active = false β†’ This should not update and generate an error.

I hope you understand what I want to do.

+7
source share
3 answers

Based on an updated question, and if I understand it correctly, I think this solution will work for you.

 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(); 
+23
source
 bool alreadyInDb = (from p in _db.SubMenus where p.UrlName = urlName select p).Count() > 0; if (alreadyInDb) { bool shouldAddRecord = (from p in _db.SubMenus where p.DisplayName == displayName && p.Active == active select p).Count() == 0; if (shouldAddRecord) { TryUpdateModel(existingMenu); _menu.Add(); } } 
+4
source
 private void Update(string urlName, string display, bool active) { item = db_.SubMenus.SingleOrDefault(x => x.UrlName == urlName); if (item == null) { // Save new item here } else { if (item.DisplayName == display && item.Active == active) { // Error, fields haven't changed and url already in db } else { // Save because fields have changed } } } 

Hope this helps!

+3
source

All Articles