1 ) Increasing the Performance of Entity Framework with Projection Queries
A standard Entity Framework query
// returns a list of Posts with all the fields
var posts = context.Posts.ToList();
Projection query to the rescue
// returns posts with only the Id and Title
var posts = context.Posts.Select(p => new
{
Id = p.Id,
Title = p.Title
}).ToList();
For custom DTO
// returns posts with only the Id and Title
var posts = context.Posts.Select(p => new PostRow
{
Id = p.Id,
Title = p.Title
}).ToList();
2 ) Disabling Lazy Loading
instead of
using (var context = new MyDbContext())
{
var users = context.Users.ToList(); // first SQL query
foreach (var user in users)
foreach (var role in user.Roles)
{
// SQL query for each user
ViewBag.Message += String.Format("User: {0} Role: {0},", user.Name, role.Name);
}
}
use below
using (var context = new MyDbContext())
{
var users = context.Users.Include(i => i.Roles).ToList();
foreach (var user in users)
foreach (var role in user.Roles)
{
ViewBag.Message += String.Format("User: {0} Role: {0},", user.Name, role.Name);
}
}
3) Disabling Lazy Loading
To avoide causes an N+1, I would recommend turning off Lazy loading. This can be done by setting the Configuration.LazyLoadingEnabled property to false in your DbContext class constructor.
to avoide the error you need to add "Include" for queries
6) To track, or not to track
When you know that you wonӴ be making changes to the entities youӲe retrieving, itӳ best for them not to be tracked by Entity Framework change tracking. You can do this by loading the entities with AsNoTracking, as seen in the following example:
_context.Posts.AsNoTracking().ToList();
Share This with your friend by choosing any social account