41

Could somebody please tell me how I check to see if a record exists, if it does exists then do nothing and if it doesn't then add the record to the database?

Please see my code below:

if (isIpnValidated == true)
{
    using (WebApplication1Entities db = new WebApplication1Entities())
    {
        Orders order = new Orders();
        order.UserId = userId;
        order.Date = System.DateTime.Now;
        order.Transaction = txnId;
        order.Amount = Convert.ToDecimal(mcGross);
        order.Email = payerEmail;
        order.Country = residenceCountry;

        db.Orderss.Add(order);
        db.SaveChanges();
    }
}

I just want to ensure no possible duplication in the database.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
iggyweb
  • 2,373
  • 12
  • 47
  • 77

2 Answers2

70

Use Any:

if (isIpnValidated)
{
    using (WebApplication1Entities db = new WebApplication1Entities())
    {
        if (db.Orderss.Any(o => o.Transaction == txnId)) return;

        Orders order = new Orders();
        order.UserId = userId;
        order.Date = System.DateTime.Now;
        order.Transaction = txnId;
        order.Amount = Convert.ToDecimal(mcGross);
        order.Email = payerEmail;
        order.Country = residenceCountry;

        db.Orderss.Add(order);
        db.SaveChanges();
    }
}
hastrb
  • 410
  • 4
  • 12
sroes
  • 14,663
  • 1
  • 53
  • 72
  • 1
    This assumes he doesn't want to update an existing record... – Maess May 14 '14 at 12:06
  • 10
    Yes, see his question: "if it does exists then do nothing" – sroes May 14 '14 at 12:08
  • 1
    I definitely don't want to update, only add if the txnId does not exist. – iggyweb May 14 '14 at 12:08
  • 1
    Can I please ask one more thing, how do I check to see if a order actually exists for a user and todays date, I've tried `if (db.Orderss.Any(o => o.UserId == userId && o.Date == System.DateTime.Now)) return;` but it doesn't appear to work. – iggyweb May 15 '14 at 13:07
  • 3
    What about `if (db.Orderss.Any(o => o.UserId == userId && o.Date.Date == System.DateTime.Today)) return;`? – sroes May 15 '14 at 13:10
  • This is very bad. It can cause bugs if used concurrently!! Just think what happens if someone inserts an order like that between `Any` and `SaveChanges`. You will have 2 duplicate orders. – Konrad Feb 20 '19 at 14:59
3
using (WebApplication1Entities db = new WebApplication1Entities())
{
   var order = db.Orders.GetAll().Where(x=> x.Transaction == txnId).FirstOrDefault();
   if(order != null) // update
   {
      //.....
      db.SaveChanges();
    }
   else
   {
      // new
   }
}
Maess
  • 4,118
  • 20
  • 29