I have this generated entity:
public partial class Player
{
public int Id { get; set; }
public string Name { get; set; }
public System.DateTime Birthdate { get; set; }
public PlayerPosition Position { get; set; }
public int IdTeam { get; set; }
public virtual Team Team { get; set; }
}
I want to make a method to update the position of a player.
I am doing this:
Player playerToUpdate = new Player
{
Id = 34,
Position=PlayerPosition.Defender
};
playersRepository.Attach(playerToUpdate);
playersRepository.UpdatePosition(playerToUpdate);
public void Attach(T entity)
{
DbSet.Attach(entity);
}
public void UpdatePosition(Player playerToUpdate)
{
Context.Entry(playerToUpdate).Property(p => p.Position).IsModified = true;
}
I get a validation exception (The name field is required)
What is the way to fix it?
Thanks.
Why aren’t you first loading the existing player, updating the position, and then saving back??
It’s an existing player – right? You obviously also have the player’s
ID…Something like:
And of course you can wrap this into a method on the
playersRepositoryof your own:and then just call that:
Entity Framework is smart enough to figure out that only the
Positionon that player has changed, so it will generate SQL something along the lines of: