0

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.

This is my Create controller

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

Can it be done this way?

Many thanks

1
  • 1
    MVC is a language agnostic architectural pattern. You should say that you're using ASP MVC, not just MVC. Commented Jan 9, 2016 at 15:04

2 Answers 2

1
db.Agreements.Any(ag=> ag.CustomerId == c)
Sign up to request clarification or add additional context in comments.

Comments

0

Method 'FirstOrDefault' return null if not found that item.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.