LINQ Query problem. Need to check if exists
I have 3 fields: urlName
开发者_如何转开发, displayName
and active
. This is check for edit record. What I want to do here is to check UrlName
is unique in Db, but at the same time, if user has already saved the Url but changed DisplayName
and Active
then the record should update.
Any one tell me how to solve that.
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();
}
updating record like
TryUpdateModel(existingMenu);
_menu.Add();
This is what I want to achieve
My other 2 values should be added in Query DisplayName and Active. Suppose "Contact" UrlName already in DB. I am loading values from dropdown returning UrlName="About", DisplayName="About Us", Active = true. Now editing record. Here are the condition to match.
1 - UrlName="About", DisplayName="About Test", Active = true --> This should update.
2 - UrlName="About", DisplayName="About Us", Active = false --> This should update.
3 - UrlName="About", DisplayName="About Test", Active = false --> This should update.
Important : 4 - UrlName="newnotexist", DisplayName="About test", Active = false --> This should update UrlName and rest if changed.
5 - UrlName="Contact", DisplayName="About Test", Active = false --> This should not update and generate error.
I hope you understand what I want to do.
Based on the 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();
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();
}
}
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!!
精彩评论