Reputation: 6967
Here's my current code
[HttpPost]
public void AddMenuItem(DateTime MenuDate, string MenuItemIds_String)
{
if (string.IsNullOrEmpty(MenuItemIds_String)) { return; }
var MenuItemIds = MenuItemIds_String.Split(',').Select(x=>int.Parse(x));
int JamaatId = 1;
object thisLcok = new object();
lock (thisLcok)
{
bool ParentPresent = db.DailyMenus.SingleOrDefault(x => x.JamaatId == JamaatId && x.MenuDate == MenuDate) != null;
if (!ParentPresent)
{
db.DailyMenus.Add(new DailyMenu { JamaatId = JamaatId, MenuDate = MenuDate, MenuNoteText = string.Empty });
db.SaveChanges();
}
}
DailyMenu parentMenu = db.DailyMenus.Single(x => x.JamaatId == JamaatId && x.MenuDate == MenuDate);
foreach(int id in MenuItemIds){
bool AlreadyExits = parentMenu.DailyMenuItems.SingleOrDefault(x => x.MenuItem == db.MenuItems.Find(id)) != null;
if (!AlreadyExits)
{
db.DailyMenuItems.Add(new DailyMenuItem { MenuItem = db.MenuItems.Find(id), DailyMenu = parentMenu });
db.SaveChanges();
}
}
}
I want to create a parent record only If does not exist. Since this an http post method. many people can post to it at the same time and multiple items can get created for the same date.
Putting lock did not solve it. Multiple items are still getting created for same date. Am I putting the lock right way ?
Upvotes: 0
Views: 207
Reputation: 1501163
Am I putting the lock right way ?
No. Let's look at your code:
object thisLcok = new object();
lock (thisLcok)
{
...
}
That's creating a new lock each time - so it's impossible that another request already owns the lock.
Your lock would need to be shared between all requests. That means it needs to be a field... either a static field (ick) or an instance field within some object which is already shared between all your requests. However, this still only works within a single AppDomain, on a single box - it's not going to scale well, or work in the face of AppDomain recycling.
It seems to me that you should probably be using database constraints to handle this instead - so check whether the record already exists, and if it doesn't, try to insert it - understanding that you will fail if another request got there in between.
Upvotes: 3