How to update only one field using Entity Framework?

前端 未结 16 1857
后悔当初
后悔当初 2020-11-22 09:09

Here\'s the table

Users

UserId
UserName
Password
EmailAddress

and the code..



        
16条回答
  •  礼貌的吻别
    2020-11-22 09:47

    In EntityFramework Core 2.x there is no need for Attach:

     // get a tracked entity
     var entity = context.User.Find(userId);
     entity.someProp = someValue;
     // other property changes might come here
     context.SaveChanges();
    

    Tried this in SQL Server and profiling it:

    exec sp_executesql N'SET NOCOUNT ON;
    UPDATE [User] SET [someProp] = @p0
    WHERE [UserId] = @p1;
    SELECT @@ROWCOUNT;
    
    ',N'@p1 int,@p0 bit',@p1=1223424,@p0=1
    

    Find ensures that already loaded entities do not trigger a SELECT and also automatically attaches the entity if needed (from the docs):

        ///     Finds an entity with the given primary key values. If an entity with the given primary key values
        ///     is being tracked by the context, then it is returned immediately without making a request to the
        ///     database. Otherwise, a query is made to the database for an entity with the given primary key values
        ///     and this entity, if found, is attached to the context and returned. If no entity is found, then
        ///     null is returned.
    

提交回复
热议问题