2

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
gigi
  • 3,846
  • 7
  • 37
  • 50

1 Answers1

2

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:

Player existingPlayer = playersRepository.GetByID(34);

existingPlayer.Position = PlayerPosition.Defender;
playersRepository.Save(existingPlayer);

And of course you can wrap this into a method on the playersRepository of your own:

public void UpdatePosition(int playerID, PlayerPosition newPosition)
{
    Player existingPlayer = playersRepository.GetByID(playerID);

    existingPlayer.Position = newPosition;
    this.Save(existingPlayer);  // assuming you have a Save method on the repository
}

and then just call that:

playersRepository.UpdatePosition(34, PlayerPosition.Defender);

Entity Framework is smart enough to figure out that only the Position on that player has changed, so it will generate SQL something along the lines of:

UPDATE dbo.Player
SET Postion = 'Defender' 
WHERE PlayerID = 34
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • In this way i will make 2 databse operations right? a select and an update. I was thinking to eliminate that select and make less database operations. – gigi Aug 26 '12 at 09:36
  • @Gigi: well, if you're that worried about two db calls, then you should wrap the `UPDATE` for each column into a stored procedure and then call that stored procedure that contains just the `UPDATE` SQL statement from the DbContext. Works - but it's **a lot of work** - and I wouldn't go "pre-optimize" if you don't really have a perf problem. **First make it work** - see if performance is OK - and if not - then optimize it to be fast.... Typically, selecting a **single row** for update is **NOT** perf critical...(assuming you have proper indexes for your search on your table) – marc_s Aug 26 '12 at 09:37