简体   繁体   中英

Microsoft.EntityFrameworkCore DbSet.Update([NotNullAttribute] TEntity entity) use case

I am relatively new to EntityFrameworkCore. I saw some code that used the Update function and that caught my attention. The question is basically "Why use it?"

What would be the difference between:

var m = await context.MyModel.Where(e => e.Id == model.Id).FirstOrDefaultAsync();
if (m != null)
{
    m.Foo = model.Foo;
    m.Bar = model.Bar;
    context.MyModel.Update(m);
    await context.SaveChangesAsync();
}

and

var m = await context.MyModel.Where(e => e.Id == model.Id).FirstOrDefaultAsync();
if (m != null)
{
    m.Foo = model.Foo;
    m.Bar = model.Bar;
    await context.SaveChangesAsync();
}

From what I've already read the Update will mark all properties within MyModel as modified, but what would the difference in result be between those two? As far as I know the modified fields will be saved regardless of "Update" when I call "SaveChanges", is the difference that if I don't "Update" the only two properties that will be modified are Foo and Bar, and in case of "Update" ALL of them will be modified? I did not find any explanation to why using "Update" would be preferable or vice versa.

Thanks.

Assuming context does not have change tracking disabled, nothing. If the entity to be updated is not being tracked by the context (eg context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; or you use context.MyModel.AsNoTracking()... for your query), then calling DbSet<T>.Update will track the entity with an EntityState of Modified . In such a case, your second example won't save any changes to the store.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM