Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Record Exists in Entity Framework [duplicate]

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.

like image 413
iggyweb Avatar asked May 14 '14 11:05

iggyweb


Video Answer


2 Answers

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();
    }
}
like image 197
sroes Avatar answered Oct 02 '22 03:10

sroes


using (WebApplication1Entities db = new WebApplication1Entities())
{
   var order = db.Orders.GetAll().Where(x=> x.Transaction == txnId).FirstOrDefault();
   if(order != null) // update
   {
      //.....
      db.SaveChanges();
    }
   else
   {
      // new
   }
}
like image 42
Maess Avatar answered Oct 02 '22 03:10

Maess