ucef
ucef

Reputation: 557

Querying database when using viewmodel on web application asp.net mvc3

I have a problem with viewmodel, when I try to add new enregistrement to my database when I have view titly typed with my viewmodel I get DbEntityValidationErrors.

This is code using viewmodel :

    [HttpPost]
    public ActionResult Create(Annonce annonce)
    {
        /*
        if (ModelState.IsValid)
        {
          */  

            _userservice.addannonce(annonce);

            return RedirectToAction("Index");
        /*
        }

       return View(new AnnonceView(annonce));
         * */
    } 

But when I use my entity domain Annonce directly on view, there is any problem. Help me please and sorry for my bad english

Upvotes: 0

Views: 81

Answers (1)

Shyju
Shyju

Reputation: 218782

I am assuimng your addannounce method is expecting an object of your EntityModel type. Not Viewmodel. ViewModel is specific to handle the View. It is not same as your Entity Model. You can not send a View Model which you created as it is to the entity framework to save it. You need to send an Entity Model. So probably you can read the values of ViewModel and set as the relevant property values of Entity Model and send that to be saved. Something like this

YoueEntity.Announce objEntityAnnounce=new YoueEntity.Announce();
//Read from the posted viewmodel and set the values to entity model.
objEntityAnnounce.ID=annonce.ID;
objEntityAnnounce.Title=annonce.Title;
//Other relevant Properties as well

_userservice.addannonce(objEntityAnnounce);

There are libraries like AutoMapper which does this mapping, You may take a look at them,

Upvotes: 1

Related Questions