2016-01-09 1 views
0

J'essaye dans asp.net MVC pour voir si un client a déjà un accord qui leur est associé. C'est ainsi que le client ne peut avoir qu'un seul contrat qui lui est assigné. J'ai regardé divers exemples Best way to check if object exists in Entity Framework? et http://www.experts-exchange.com/questions/28371483/MVC-Controller-Check-If-A-Record-Exists-Before-inserting-Call-a-method.html mais n'arrive pas à les faire fonctionner dans ma solution. Je voudrais l'avoir dans la méthode Créer une action.Comment vérifier si un enregistrement existe déjà dans la base de données en utilisant asp.Net MVC

Ceci est mon contrôleur Créer

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

Peut-il être fait de cette façon?

Un grand merci

+1

MVC est un langage agnostique modèle architectural. Vous devriez dire que vous utilisez ASP MVC, et pas seulement MVC. –

Répondre

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

Méthode de retour 'FirstOrDefault' null si introuvable cet article.

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