Title: ASP.NET MVC 5: Query fails to return data using IdentityDbContext in UnitOfWork Pattern
Tags: asp.net-mvc;entity-framework;ef-code-first
Question: I am trying to extend the UnitOfWork pattern that I used for a number of MVC 4 applications to MVC 5 whilst also using the new IdentityDbContext and things are not working out. The problem is its very hard to debug as no errors are being generated.

First, some code.

I have a context definition that looks as follows. I have added my own DbSets to the out of the box IdentityDbContext as it makes sense to keep everything in one place.

```public class ApplicationDbContext : IdentityDbContext<ApplicationUser&gt;
{
    public DbSet<PALSOfficer&gt; PALSOfficers { get; set; }
    public DbSet<Client&gt; Clients { get; set; }
    public DbSet<GP&gt; GPs { get; set; }
    public DbSet<Surgery&gt; Surgeries { get; set; }
    public DbSet<Disability&gt; Disabilities { get; set; }
    public DbSet<Area&gt; Areas { get; set; }
    public DbSet<PALSReferral&gt; PALSReferrals { get; set; }
    public DbSet<Appointment&gt; Appointments { get; set; }

    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }



}
```

I then have a UnitOfWork class that looks as follows:

```public class UnitOfWork : IDisposable
{
    private bool _disposed = false;
    private ApplicationDbContext _context = new ApplicationDbContext();
    public UserManager<ApplicationUser&gt; _userManager { get; set; }

    private PalsOfficerRepository _palsOfficerRepository;
    private UserRepository _userRepository;
    private GenericRepository<Area&gt; _areaRepository;

    public UserRepository UserRepository
    {
        get
        {
            if (this._userRepository == null)
            {
                this._userRepository = new UserRepository(_context);
            }
            return _userRepository;
        }
    }

    public PalsOfficerRepository PalsOfficerRepository
    {
        get
        {
            if (this._palsOfficerRepository == null)
            {
                this._palsOfficerRepository = new PalsOfficerRepository(_context);
            }
            return _palsOfficerRepository;
        }
    }

    public GenericRepository<Area&gt; AreaRepository
    {
        get
        {
            if (this._areaRepository == null)
            {
                this._areaRepository = new GenericRepository<Area&gt;(_context);
            }
            return _areaRepository;
        }
    }

    public UserManager<ApplicationUser&gt; UserManager
    {
        get
        {
            if (this._userManager == null)
            {
                this._userManager = new UserManager<ApplicationUser&gt;(new UserStore<ApplicationUser&gt;(_context));
            }
            return _userManager;
        }
    }



    public void Save()
    {
        try
        {
            _context.SaveChanges();
        }
        catch (DbEntityValidationException dbEx)
        {
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                }
            }
            throw;
        }
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (this._userManager != null)
            { this._userManager.Dispose(); }
            _userManager.Dispose();
        }
        this._disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
```

So far so good. I am using code first to generate my database with automatic migrations.

My problem is that if I try to query the database, odd things happen. Take this method for instance.

```var results = new SearchResults<PALSOfficer&gt;();

        var officers = from o in Context.PALSOfficers
                       select o;

        if (!string.IsNullOrEmpty(keyword))
        {
            officers = (from o in officers
                        where o.FirstName.Contains(keyword) || o.LastName.Contains(keyword)
                        select o);

        }

        officers = officers.OrderBy(p =&gt; p.LastName);
        results.Total = officers.Count();
        int offset = page * display;
        results.ResultList = results.Total &gt; offset ? officers.Skip(offset).Take(display) : officers;

        //results.ResultList = Context.PALSOfficers;

        return results;
```

This returns nothing even though the database contains data. Weirdly, the count will work. If I put a breakpoint in and mouseover the results I get the message that 'children could not be evaluated'

If I simply return ```Context.PALSOfficers``` I get the rows back. Any type of manipulation of that data though (sorting etc) seems to break the query entirely.

Here is the definition of PALSOfficer

```public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public DateTime Added { get; set; }
    public DateTime Updated { get; set; }
}

public class PALSOfficer : ApplicationUser
{
    public string InternalReference { get; set; }
    public virtual ICollection<Area&gt; Areas { get; set; }
}
```

Comment: Ok, so I bypassed the whole UnitOfWork class and instead tried by just creating a new context and querying and it still doesnt work. Also, I am noticing that the first time the query runs it can take upward of 20 seconds for the database to come back.

Comment: Your question is really hard to answer as is: try writing a Short, Self Contained, Correct (Compilable), Example -- http://sscce.org/



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2013:00:10/25/13', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<asp.net-mvc><entity-framework><ef-code-first>', 'Title': 'ASP.NET MVC 5: Query fails to return data using IdentityDbContext in UnitOfWork Pattern', 'ViewCount': 622, 'id': 19601120, 'user_AboutMe': None, 'user_AccountId': 59706.0, 'user_DisplayName': 'Sergio', 'user_Reputation': 9591.0, 'user_Views': 948.0, 'user_id': 178570.0}}