如何使用asp.Net MVC检查数据库中是否已存在记录 [英] How to check if a record already exists in the db using asp.Net MVC

查看:37
本文介绍了如何使用asp.Net MVC检查数据库中是否已存在记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在asp.net MVC中尝试查看客户是否已经与他们建立了协议.这样,客户只能分配1个协议.我看过各种示例检查对象是否存在的最佳方法是否存在于Entity Framework中?

I'm trying in asp.net MVC to see if a customer has already got an agreement associated to them. This is so the customer can only have 1 agreement assigned to them. I have looked at various examples Best way to check if object exists in Entity Framework? and http://www.experts-exchange.com/questions/28371483/MVC-Controller-Check-If-A-Record-Exists-Before-inserting-Call-a-method.html but can't seem to get them working in my solution. I would like to have it in the Create Action method.

这是我的创建"控制器

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

可以这样吗?

非常感谢

推荐答案

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

这篇关于如何使用asp.Net MVC检查数据库中是否已存在记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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