The NeceMoon | My 12 Favorite Entity Framework Tricks

My 12 Favorite Entity Framework Tricks

by necemon 12. December 2015 22:45

The Entity Framework is an ORM system, a set of technologies that support the development of data-oriented software applications. It's part of the .NET Framework. I have been playing with it for a couple of years and here are my top tips :


1. Extending the TimeOut value
When loading large amounts of data, the operations happen to fail every time they hit the default time out, so it may be a good idea to extend it to a few hours.
Doing it when initializing the Context object ensures that it's all set before any database call.


2. Second Level Caching
That's a caching of query results. The results of SQL commands are stored in the cache, so that the same SQL commands retrieve their data from the Cache rather than executing the query again against the underlying provider. This can have a performance boost for your application and results in less activity against your database. To enable this feature, you can download and implement this open source project.


3. Dynamic Code First and database migration
EF allows you to program against a model without having to deal with a database directly. With the Code-First approach, you can focus on the domain design and start creating classes. Code-First APIs will create/update the database on the fly based on your entity classes and configuration.
By the way, while we are on the topic on configuration, you can do it all within your C# code. Here are a couple of handy properties:
AutomaticMigrationEnabled : Set it to true to enable the Code-First magic
AutomaticMigrationDataLossAllowed : a value indicating if data loss is acceptable during automatic migration. If set to false an exception will be thrown when data loss may occur as part of an automatic migration.


4. Previewing Code-First change details
There is an easy way to generate the SQL scripts that EF plans to execute, before/without actually commiting those changes. It goes like this:
var configuration = new MigrationConfiguration();
var migrator = new DbMigrator(configuration);
var scriptor = new MigratorScriptingDecorator(migrator);
string script = scriptor.ScriptUpdate(null, null);
It could be useful if you want to make some changes to that script, or if you are debugging an issue or if you are just curious about what's going on :-)


Multiple Active Result Sets (MARS) is a feature that allows the execution of multiple batches on a single connection. To say it in a simple way, you can make a connection to server and then submit multiple requests to server at the same time, and then read results from these requests in whatever way you want. Just include "MultipleActiveResultSets=True" in your web.config file.


6. Setting all the properties constraints in a single place
For example, instead of adding an attribute to each string property, you could set a default string maximum length as follow:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
       modelBuilder.Properties<String>().Configure(p => p.HasMaxLength(360));


7. Inheritance strategy
EF has many ways of dealing with inheritance
-Table per hierarchy : a single table with all based and derived class properties (A discriminator property being used to differenciate between them)
-Table per type : base properties on the base table, and for each derived class, derived properties on a separate table
-Table per concrete type : each derived class  gets its own table with all (based or derived) properties.
Pretty extensive, the only case I am not sure about : is there a way to make EF not deal with inheritance at all ? I mean, assuming A derives from B, is there a way to make EF treats A and B as completely different classes and ignore the fact that that one inherits from the other ?
Not a very common scenario, but just for the sake of avoiding duplication, I could want to use inheritance in the C# code so that I don't copy the properties twice in different classes but I wouldn't want to involve any reaction from EF. TPC comes close to that, but the classes still share the same primary key.


8. EntityFunctions Methods
When using LINQ to Entity Framework, your predicates inside the Where clause get translated to SQL, which doesn't have a translation for some complex constructions like DateTime.AddDays(). That's where EntityFunctions methods come in the picture.


9. LINQKit
LINQKit is a free set of extensions for LINQ to SQL and Entity Framework power users. I mostly use it to dynamically build predicates and insert expression variables in subqueries, but it also allow to :
- Plug expressions into EntitySets and EntityCollections
- Combine expressions (have one expression call another)
- Leverage AsExpandable to add your own extensions.


10. Lazy Loading
One of the most interesting Entity Framework features is the Lazy Load function, which is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed.
To put it simply, lazy loading means delaying the loading of related data, until you specifically request for it.
This could be enabled by setting the Configuration.LazyLoadingEnabled property to true.


11. AsNoTracking
Entity Framework exposes a number of performance tuning options to help you optimise the performance of your applications. One of these tuning options is .AsNoTracking(). This optimisation allows you to tell Entity Framework not to track the results of a query. This means that Entity Framework performs no additional processing or storage of the entities which are returned by the query.
There are significant performance gains to be had by using AsNoTracking().


12. Staying away from performance traps and other EF gotchas
The object context manager can lead to situations where EF behaves in surprising ways. It's good to be aware of the patterns that you can follow to avoid these pitfalls.

Tags: , , ,

English | Technical

blog comments powered by Disqus


I am Necemon Yai. I am a .NET developer and a digital artist. Let's keep in touch via Twitter, LinkedIn or Facebook.

Je suis Necemon Yai. Je suis un développeur .NET et un artiste numérique. Restons en contact via Twitter, LinkedIn ou Facebook.