I hope this is an easy one.
Using MVC4 with Entity Framework 4.1.
I’am trying to update a model with some properties passed through from a View with a custom view model’s properties.
I have this class.
public class SitePage
{
public System.Guid PageID { get; set; }
public int PageTypeID { get; set; }
public string PageTitle { get; set; }
public Nullable<int> RegionId { get; set; }
public Nullable<int> LockLevelId { get; set; }
public System.DateTime UpdatedDate { get; set; }
public System.Guid UpdatedById { get; set; }
public System.Guid CreatedById { get; set; }
public System.DateTime CreatedDate { get; set; }
public string Url { get; set; }
public int PageStateId { get; set; }
public string SummaryImage { get; set; }
}
My controller
public ActionResult Update(AddPageViewModel model)
{
if (ModelState.IsValid)
{
var g = new Guid(model.PageId);
SitePage UpdatePage = dbSite.SitePages.FirstOrDefault(m => m.PageID == g);
//This is a page update. Not updating all properties
UpdatePage.PageTitle = model.PageTitle;
UpdatePage.GetFirstSection.PageSectionText.PageText = model.PageText;
UpdatePage.PageTypeID = (int)SitePageType.PageTypes.CommunityPage;
UpdatePage.RegionId = model.Region
UpdatePage.CreatedById = userId;
UpdatePage.CreatedDate = DateTime.UtcNow;
UpdatePage.UpdatedById = userId;
UpdatePage.UpdatedDate = DateTime.UtcNow;
TryUpdateModel(UpdatePage);
dbSite.Save();
return RedirectToAction("Community_test", "Community", new { id = UpdatePage.Url });
}
else
{
return RedirectToAction("Community_test", "Community");
}
}
Passing this page view model to the controller
public class AddPageViewModel
{
public string PageTitle { get; set; }
public string PageText { get; set; }
public int Region { get; set; }
public string TagString { get; set; }
public string ParentPageId { get; set; }
public string PageId { get; set; }
}
If i debug I can see that the SitePage instance UpdatePage has all the correct values when TryUpdateModel is called. However all values except RegionId are updated correctly in the db. RegionId gets set as null. If i run a trace on the server the sql entity framework generates is indeed setting RegionId to null even though my model has a value. This problem is intermittent! Some times it works, other it doesnt. 1 in 4 will update correctly and i cant quite see where im going wrong. Im newish to this stuff really.
Our classes are generated from the database and we are using an edmx file. Im not sure if i can make any changes to these classes without them just being overridden the next time we update model from database.
Any ideas or more info needed, give me a shout. Cheers
TryUpdateModel takes the values from the form and populate the given model. This means that setting any values on
UpdatePageisn’t necessary.It is good practice to also specify the properties that should be updated.
Regarding RegionId getting set to Null.
Before
TryUpdateModelis called or right after?