如何使用asp.Net MVC检查数据库中是否已存在记录

时间:2016-01-09 15:00:21

标签: asp.net-mvc

我正在尝试使用asp.net MVC来查看客户是否已经获得了与他们相关的协议。这样客户只能分配1份协议。我查看了各种示例Best way to check if object exists in Entity Framework?http://www.experts-exchange.com/questions/28371483/MVC-Controller-Check-If-A-Record-Exists-Before-inserting-Call-a-method.html,但似乎无法让他们在我的解决方案中工作。我想在Create Action方法中使用它。

这是我的创建控制器

     public ActionResult Create()
    {
        ViewBag.CustomerId = new SelectList(db.Customers, "CustomerID", "LastName");
        ViewBag.SupplierId = new SelectList(db.Suppliers, "SupplierId", "SupplierName");
        return View();
    }

    // POST: Agreements/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "AgreementId,CustomerId,SupplierId")] Agreement agreement)
    {
        //Trying to check here before the create 
        /*
        var exists = (from c in db.Agreements
                   where c.CustomerId == C)
        */

        if (ModelState.IsValid)
        {
            agreement.AgreementId = Guid.NewGuid();
            db.Agreements.Add(agreement);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.CustomerId = new SelectList(db.Customers, "CustomerID", "LastName", agreement.CustomerId);
        ViewBag.SupplierId = new SelectList(db.Suppliers, "SupplierId", "SupplierName", agreement.SupplierId);
        return View(agreement);
    }

可以这样做吗?

非常感谢

2 个答案:

答案 0 :(得分:1)

db.Agreements.Any(ag=> ag.CustomerId == c)

答案 1 :(得分:0)

方法'FirstOrDefault'如果找不到该项,则返回null。

var foo = db.FooTable.FirstOrDefault(w => w.Id == Id); if (foo == null) { }