检查实体框架中是否存在记录
本文关键字:存在 记录 是否 实体 框架 检查 | 更新日期: 2023-09-27 18:03:30
有人能告诉我我如何检查,看看记录是否存在,如果它确实存在,然后什么都不做,如果它不那么添加记录到数据库?
请参阅下面我的代码:
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();
}
}
我只是想确保在数据库中没有可能的重复
使用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();
}
}
using (WebApplication1Entities db = new WebApplication1Entities())
{
var order = db.Orders.GetAll().Where(x=> x.Transaction == txnId).FirstOrDefault();
if(order != null) // update
{
//.....
db.SaveChanges();
}
else
{
// new
}
}