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