【问题标题】:How to check if a record already exists in the db using asp.Net MVC如何使用asp.Net MVC检查数据库中是否已存在记录
【发布时间】:2017-09-08 04:28:50
【问题描述】:

我正在 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);
    }

这样可以吗?

非常感谢

【问题讨论】:

  • MVC 是一种与语言无关的架构模式。您应该说您使用的是 ASP MVC,而不仅仅是 MVC。

标签: asp.net-mvc


【解决方案1】:
db.Agreements.Any(ag=> ag.CustomerId == c)

【讨论】:

    【解决方案2】:

    如果没有找到该项目,方法 'FirstOrDefault' 返回 null。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 2013-08-07
      • 2016-07-15
      相关资源
      最近更新 更多