I have a view especially designed for editing general project infos (name, description, …). I have another view especially designed for changing the image attached to a project.
Here is the base model of a project
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; }
}
Here is the view model for editing basic project infos
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; }
}
Here is the view model for changing the image attached to a project
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; }
}
So far so good. The problem occured when I edit a project through my view (the first one for editing basic infos) and submit changes. Then the action in the controller is fired and the following code is executed:
[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");
}
As you can see, I map the view model in a project model, then I save this object.
And here is the code executed in the repository
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();
}
The problem is that if I previously had an image attached to the project in the repository, then my image is lost during this process because the object passed to the repository didn’t content any image.
Do you see what I mean? How do I have to manage this problem?
I like the idea of having view models only containing necessary infos. The problem occur when saving these partial infos to the original object without losing data.
Thanks.
I suggest you to pull the
projectentry from the database first, then applying the changes from view model, and then saving the result: