2011-11-25 43 views
1

我有一個專門用於編輯常規項目信息(名稱,說明,...)的視圖。我有另一種視圖,專門用於更改附加到項目的圖像。將視圖模型保存到存儲庫時會丟失一些數據

這裏是一個項目

public class Project 
{ 
    [Key] 
    public int ProjectID   { get; set; } 
    public string Name    { get; set; } 
    public string Description  { get; set; } 
    public string Category   { get; set; } 
    public string Client   { get; set; } 
    public int Year    { get; set; } 
    public byte[] Image    { get; set; } 
    public string FileName   { get; set; } 
    public int FileLength  { get; set; } 
    public string FileType   { get; set; } 
} 

這裏的基本模型是用於編輯基本項目的相關信息

public class ProjectViewModel 
{ 
    public int ProjectID  { get; set; } 
    public string Name   { get; set; } 
    public string Description { get; set; } 
    public string Category  { get; set; } 
    public string Client  { get; set; } 
    public int Year   { get; set; } 
} 

這裏視圖模型被用於改變連接到項目

圖像視圖模型
public class UploadImageViewModel 
{ 
    public int  ProjectID { get; set; } 
    public byte[] Image  { get; set; } 
    public string FileName { get; set; } 
    public int  FileLength { get; set; } 
    public string FileType { get; set; } 
} 

到目前爲止好。當我通過我的視圖編輯項目(第一個編輯基本信息)並提交更改時,出現問題。然後在控制器中的動作被觸發並執行以下代碼:

[HttpPost] 
    public ActionResult EditProject(ProjectViewModel viewModel) 
    { 
     if (!ModelState.IsValid) 
      return View(); 

     // Map viewModel into model 
     Project model = Mapper.Map<ProjectViewModel, Project>(viewModel); 

     m_AdminService.SaveProject(model); 

     return RedirectToAction("ListProjects"); 
    } 

正如你所看到的,我視圖模型映射在項目模型,然後我保存這個對象。

這裏是在倉庫中執行的代碼

public void SaveProject(Project project) 
    { 
     if (project.ProjectID == 0) 
     { 
      m_Context.Projects.Add(project); 
     } 
     else 
     { 
      var entry = m_Context.Entry(project); 
      entry.State = EntityState.Modified; 
     } 

     m_Context.SaveChanges(); 
    } 

的問題是,如果我以前有附加到項目存儲庫中的圖像,然後我的形象在此過程中,因爲傳遞的對象丟失到存儲庫沒有任何圖像內容。

你明白我的意思了嗎?我該如何解決這個問題?

我喜歡觀看只包含必要信息的模型。將這些部分信息保存到原始對象而不丟失數據時會發生問題。

謝謝。

回答

1

我建議你先拉從數據庫中project條目,然後從應用視圖模型的變化,然後保存結果:

Project model = m_AdminService.LoadProject(viewModel.ProjectID); 

Mapper.Map<ProjectViewModel, Project>(target: model, source: viewModel); 
// I'm not sure how the mapper works, you may have to write other code instead 

m_AdminService.SaveProject(model); 
+0

可惜,這是行不通的。在注入數據之前,automapper會清除目標對象中的所有內容。所以即使我先從數據庫中取出項目,它也會被automapper清除。 – Bronzato

+0

也許切換到另一個映射器是可行的嗎? – Zruty

+0

最後,上面的解決方案工作。謝謝。 – Bronzato