EntityFramework Tips PDF
EntityFramework Tips PDF
This small PDF gives some tips and tricks with regards to Entity Framework. The examples were taken from "Tips and tricks". The following tips
are in this PDF:
Don't track readonly entities
In-Memory database with SQLite
LoadAsync - Split queries into smaller chunks
.ToListAsync();
✅ Good Explicitly say that the entities are not tracked by EF.
return await blogPosts.Where(b => b.IsPublished)
.Include(b => b.Tags)
.AsNoTracking()
.ToListAsync();
Benchmark
A detailed setup and benchmark (which is referred below) can be found on the official https://docs.microsoft.com/en-
us/ef/core/performance/efficient-querying#tracking-no-tracking-and-identity-resolution.
| Method | Blogs | PostsPer | Mean | Error | StdDev | Median | Ratio | Gen 0 | Gen 1 | Allocated |
connection.Open();
services.AddDbContext<MyDbContext>(options =>
options.UseSqlite(connection);
});
To make it work with multiple connections at a time, we can utilize the cache=shared identifier for the data source. More information can be
found on the official website.
var connection = new SqliteConnection("DataSource=myshareddb;mode=memory;cache=shared");
connection.Open();
services.AddDbContext<MyDbContext>(options =>
options.UseSqlite(connection);
});
.ToListAsync();
[a0].[Nationality], [a0].[PlaceOfBirth]
LEFT JOIN (
With LoadAsync :
var query = Context.Books;
LEFT JOIN (
❌ Bad Not defining the maximum length of a string will lead to NVARCHAR(max) .
public class BlogPostConfiguration : IEntityTypeConfiguration<BlogPost>
✅ Good Defining the maximum length will reflect also in the database table.
public class BlogPostConfiguration : IEntityTypeConfiguration<BlogPost>
.ToListAsync();
✅ Good Get all related children by a separate query which gets resolved by an INNER JOIN .
var blogPosts = await DbContext.Blog
.AsSplitQuery();
.ToListAsync();
💡 Info: There are database which support multiple result sets in one query (for example SQL Server with Multiple Active Result Set). Here
the performance is even better. For more information checkout the official Microsoft page about SplitQuery .