I am trying to update only some of the fields in a table. I created a view model with the fields that need to be updated. There are other fields in the table that don't need to be touched so they have been left oiut of the view model.
When I execute SaveChanges(), I get an error about a field not included in the view model, cannot be NULL. Since this is a partial update, I thought the fields not included in the view model should just be left alone on the update.
The Exception:
Cannot insert the value NULL into column 'NewClubName', table 'dbo.NewClub';
column does not allow nulls. UPDATE fails
Here is what I have:
//View Model
public class FormANewClubTeamViewModel
{
/******************************************************
Properties for Domain Model "NewClub"
*******************************************************/
public int NewClub_Id { get; set; }
//District and Division
public string District { get; set; }
public string Division { get; set; }
//Lt Governor
public string LtGovMasterCustomerId { get; set; }
public string LtGovContact { get; set; }
public string LtGovEmail { get; set; }
public string LtGovPhone { get; set; }
// Club Counselor
public string ClubCounselorMasterCustomerId { get; set; }
[Display(Name = "Club counselor")]
[Required(ErrorMessage = "Club counselor name")]
public string ClubCounselorContact { get; set; }
[Display(Name = "Club counselor email")]
[Required(ErrorMessage = "Club counselor email")]
public string ClubCounselorEmail { get; set; }
[Display(Name = "Club counselor phone")]
[Required(ErrorMessage = "Club counselor phone")]
public string ClubCounselorPhone { get; set; }
/******************************************************
Properties for Domain Model "NewClubSponsor"
*******************************************************/
public List<NewClubSponsor> Sponsors { get; set; }
}
//Controller doing the update
if (ModelState.IsValid)
{
if (model.NewClub_Id > 0)
{
httpStatus = HttpStatusCode.OK;
NewClub newClub = new NewClub
{
Id = model.NewClub_Id,
ClubCounselorMasterCustomerId = model.ClubCounselorMasterCustomerId,
ClubCounselorContact = model.ClubCounselorContact,
ClubCounselorEmail = model.ClubCounselorEmail,
ClubCounselorPhone = model.ClubCounselorPhone,
DateUpdated = DateTime.Now
};
db.NewClubs.Add(newClub);
db.Entry(newClub).State = EntityState.Modified;
try
{
var dbResult = db.SaveChanges() > 0;
}
catch (SqlException ex)
{
[...]
}