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

问题描述

大家好,我们想知道是否有人可以告诉我,如果我在正确的道路上,我试图检查数据库中是否存在数据(iccid)。检查下面的代码。



Hi guys wondering if guys could tell me if i'm on the right path, im trying to check if data(iccid) exists in database. Check code below.

public ActionResult Add(SIMCardInfoView model)
        {
            if (ModelState.IsValid)
            {
                SIMCard simCard = null;
                //Check if entity exists in database 
                simCard = db.SIMCards.FirstOrDefault(card => card.ICCID == model.ICCID);

                if (model.IsNew)
                {
                    // The posted model indicated this is a new simcard.
                    simCard = new SIMCard();
                    db.SIMCards.Add(simCard);
                }
                else
                {
                    // This model already exists
                    // The entity could not be saved, add an error and return to the view.
                    ModelState.AddModelError("Validation", "Unable to save this simcard. The database entity exists in the database.");
                    UpdateDetailViewModel(model);
                    return View(model);
                }

                //TODO:Default group
                //simCard.GroupID = 1;
                simCard.CapturedBy = "Test";
                simCard.DateCaptured = DateTime.Now;
                simCard.ICCID = model.ICCID;
                simCard.IMSI = model.IMSI;
                simCard.MSISDN = model.MSISDN;
                simCard.NetworkID = model.NetworkID;
                simCard.PackageID = model.PackageID;
                simCard.SIMCardID = model.SIMCardID;
                simCard.SubBatchID = model.SubBatchID;
                simCard.TrackingCode = model.TrackingCode;

                db.SaveChanges();
                return RedirectToAction("Index");
            }
            else
            {
                // The user did not post a valid model.
                // To debug this, check the errors inside the modelstate object.
                UpdateDetailViewModel(model);
                return View(model);
            }
        }





有人可能会指出我出错的地方我知道我在这里是个菜鸟。



Can someone maybe point out where i went wrong i know im being a noob here.

推荐答案

bool hasData = db.SIMCards.Any(card => card.ICCID == model.ICCID);
if (hasData ){
  // entity exists in database
}
else {
  // nope, not exists in database
}


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

08-29 16:54