简体   繁体   中英

When to disable proxy generation and use AsNoTracking?

In my WebApi project, I use EF6, follow Uow and generic repository patterns, and I also map my models to dto's and vice-versa.

Currently I set the following when creating the dbContext :

this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;

I also use AsNoTracking when fetching data from the db.

When updating the db, I'm using the dbContext directly to attach the entities when handling small entities (ie. no relationships). I use GraphDiff for complex entities (ie. with relationships).

When enabling proxies and tracking, and even with disabling them, I noticed that the SQL statement sent to the DB includes all the table's columns, instead of only those columns that have been actually changed.

However, GraphDiff is loading the entity again before saving the changes to the DB. The SQL statement in this case also contains all the columns. Is this the correct behavior?

So, in my scenario, is it safe to disable proxies and tracking as I'm dealing with detached entities?

Yes, I guess it is; this is a way for EF to handle optimistic concurrency.

Optimistic concurrency involves optimistically attempting to save your entity to the database in the hope that the data there has not changed since the entity was loaded. If it turns out that the data has changed then an exception is thrown and you must resolve the conflict before attempting to save again.

The only way for EF to check this is to load all the columns, checks for any changes and block the save if it gets that the record got modified between the last load and your save. Check this .

If you don't have a timestamp column you can use this attribute (more info here ) [ConcurrencyCheck] to inform EF that that specific column is the column to use to understand if the record changed; this should avoid loading all for concurrency check.

Hope it helps :)

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