Reputation: 571
I have an MVC 4 sample application using code first (POCO), EF, ViewModels and AutoMapper. I have created a controller where parent and corresponding child entities are on the same view (entity with nested collection of child entities). Looks good so far except I am having problem with updating records. I am getting the following error:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
I have been searching online for many days now trying out different solutions but couldn't get it working.
I have the following domain models:
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Player> Players { get; set; }
}
public class Player
{
public int Id { get; set; }
public string Name { get; set; }
public int TeamId { get; set; }
public virtual Team Team { get; set; }
}
And corresponding viewmodels:
public class TeamVM
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<PlayerVM> Players { get; set; }
}
public class PlayerVM
{
public int Id { get; set; }
public string Name { get; set; }
public int TeamId { get; set; }
public virtual TeamVM Team { get; set; }
}
My mapping is as follows:
Mapper.CreateMap<Player, PlayerVM>();
Mapper.CreateMap<PlayerVM, Player>();
Mapper.CreateMap<Team, TeamVM>();
Mapper.CreateMap<TeamVM, Team>();
My team controller edit action is as follows:
[HttpPost]
public ActionResult Edit(TeamVM teamVM)
{
if (ModelState.IsValid)
{
Team team = context.Teams.Find(teamVM.Id);
Team updatedTeam = Mapper.Map<TeamVM, Team>(teamVM, team);
context.Entry(team).CurrentValues.SetValues(updatedTeam);
context.SaveChanges();
return RedirectToAction("Index");
}
return View(teamVM);
}
What am I missing here?
Upvotes: 3
Views: 1532
Reputation: 109118
It's about the last part of the exception:
or the unrelated object must be deleted
It looks like in your Edit
method Player
s are removed from team.Players
(or maybe even cleared altogether because of copy failures). But, too bad, you can't just remove items from a child collection if the foreign key is not nullable (apparently, players can't exist without team). You have to remove the deleted players from the context.
So you must detect the players that are removed from the team and for each of them call
context.Players.Remove(player);
Upvotes: 2