检查实体框架中是否存在记录 [英] Check if Record Exists in Entity Framework

查看:70
本文介绍了检查实体框架中是否存在记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我如何检查记录是否存在,如果确实存在,则什么也不做,如果不存在,则将该记录添加到数据库中?

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.

推荐答案

使用任何

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

这篇关于检查实体框架中是否存在记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆