When to disable proxy generation and use AsNoTracking?

asp.net-web-api c# ef-code-first entity-framework graphdiff


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?

3/18/2016 5:15:34 AM

Accepted Answer

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 :)

3/18/2016 9:15:10 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow