2012-04-22 18 views
0

我有一個viewmodel的問題,當我嘗試添加新的enregistrement到我的數據庫時,我查看titly鍵入我的viewmodel我得到DbEntityValidationErrors在Web應用程序asp.net上使用viewmodel時查詢數據庫mvc3

這是代碼中使用視圖模型:

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

      _userservice.addannonce(annonce); 

      return RedirectToAction("Index"); 
     /* 
     } 

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

但是,當我直接用我的實體域Annonce上來看,有任何問題。請幫助我,對不起我的英語不好

回答

1

我想你的addannounce方法期待你的EntityModel類型的對象。不是Viewmodel。 ViewModel特定於處理視圖。它與你的實體模型不一樣。您無法將您創建的視圖模型發送給實體框架以進行保存。你需要發送一個實體模型。因此,可能你可以讀取ViewModel的值,並設置爲實體模型的相關屬性值併發送以保存。這樣

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

有喜歡AutoMapper這確實該測繪,你可以看看他們的庫,

+0

感謝Shyju先生東西,我明白你的意思,但我不希望使用automapper,我沒有時間去看它,這是我的觀點模型 – ucef 2012-04-22 22:05:20

+0

@ucef:然後你可以像我在答案中那樣手動地圖。 – Shyju 2012-04-22 22:20:45

+0

謝謝Shyju先生,我在方法'create(Annonceview annonceview)'方面犯了錯誤,但addannonce方法採用參數化方法,這是我的實體,我沒有時間學習automapper。最好的祝福 – ucef 2012-04-22 22:27:05

相關問題