检查实体框架中是否存在记录

时间:2014-05-14 11:56:48

标签: c# entity-framework

有人可以告诉我如何检查记录是否存在,如果它确实存在则不执行任何操作,如果不存在则将记录添加到数据库中?

请参阅下面的代码:

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

我只想确保数据库中没有可能的重复。

2 个答案:

答案 0 :(得分:27)

使用Any

if (isIpnValidated == true)
{
    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();
    }
}

答案 1 :(得分:1)

using (WebApplication1Entities db = new WebApplication1Entities())
{
   var order = db.Orders.GetAll().Where(x=> x.Transaction == txnId).FirstOrDefault();
   if(order != null) // update
   {
      //.....
      db.SaveChanges();
    }
   else
   {
      // new
   }
}