DbSet.Attach(entity) vs DbContext.Entry(entity).State = EntityState.Modified

后端 未结 3 736
猫巷女王i
猫巷女王i 2020-11-28 17:42

When I am in a detached scenario and get a dto from the client which I map into an entity to save it I do this:

context.Entry(entity).State = EntityState.Mod         


        
3条回答
  •  囚心锁ツ
    2020-11-28 18:16

    When you use the DbSet.Update method, Entity Framework marks all properties of your entity as EntityState.Modified, so tracks them. If you want to change only some of your properties, not all of them, use DbSet.Attach. This method makes all of your properties EntityState.Unchanged, so you must make your properties that you want to update EntityState.Modified. Thus when the app hits to DbContext.SaveChanges, it will only operate modified properties.

提交回复
热议问题