如何更新Entity Framework 4.5中的特定列?

时间:2012-08-26 09:26:43

标签: c# entity-framework

我有这个生成的实体:

    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; }
    }

我想制作一种方法来更新玩家的位置。

我这样做:

        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;
        }

我收到验证异常(名称字段是必需的

修复它的方法是什么?

感谢。

1 个答案:

答案 0 :(得分:2)

为什么不首先加载现有的播放器,更新位置,然后保存?

这是现有的玩家 - 对吗?你显然也有玩家的ID ...

类似的东西:

Player existingPlayer = playersRepository.GetByID(34);

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

当然,你可以将它包装到你自己playersRepository的方法中:

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
}

然后打电话给:

playersRepository.UpdatePosition(34, PlayerPosition.Defender);

实体框架足够聪明,可以发现只有该播放器上的Position发生了变化,因此它会产生类似以下内容的SQL:

UPDATE dbo.Player
SET Postion = 'Defender' 
WHERE PlayerID = 34