C# Question

Poor performance when loading entity with large string property using Entity Framework

Given an entity and a DbContext like the following:

public class Entity
{
public int Id {get;set;}
public string LargeString {get;set;}
}

public class MyDbContext : DbContext
{
public DbSet<Entity> Entities {get;set;}
}


And an entity stored in the database with
Id
42 and
LargeString
containing some two megabytes of XML. The following takes half a minute or so, and occasionally gives
OutOfMemoryException
:

using (var dbContext = new MyDbContext())
{
var entity = await dbContext.Entities.SingleAsync(e => e.Id == 42);
}


At the same time, the following Dapper query executes in miliseconds:

using (var dbContext = new MyDbContext())
{
var entity = await dbContext.Database.Connection
.Query<Entity>("SELECT Id, LargeString FROM Entities WHERE Id = 42")
.SingleAsync();
}


Is it possible to somehow hint Entity Framework that the
LargeString
property could be this large (in a way that would make Entity Framework perform acceptable in this scenario).

Answer

I had the same issue yesterday. What I did find out is that async operations with Entity Framework is broken or at least very slow. Try using the same operations synchronously:

using (var dbContext = new MyDbContext())
{
    var entity = dbContext.Entities.Single(e => e.Id == 42);
}

Also read the post by rducom here: http://stackoverflow.com/a/28619983/7108481

Comments