有人可以告诉我如何检查记录是否存在,如果它确实存在则不执行任何操作,如果不存在则将记录添加到数据库中?
请参阅下面的代码:
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();
}
}
我只想确保数据库中没有可能的重复。
答案 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
}
}