Search code examples
asp.netentity-frameworkasp.net-identityentity-framework-coreasp.net-identity-3

Including Identity User with Entity Framework doesn't work


I am having trouble including my Identity User in query results. Other entities are included just fine, no matter how many levels deep.

Here's the model I'm using.

Building * --- 1 City
     *            *
     |          /
     |         /
     1        1
ApplicationUser

And the context:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<City> Cities { get; set; }
    public DbSet<Building> Buildings { get; set; }
}

Both Building and City have these properties:

public Guid ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }

The query I'm using to retrieve data:

var building = context.Buildings
    .Include(c => c.ApplicationUser)
    .Include(c => c.City)
    .Include(c => c.City.ApplicationUser)
    .First();

In the result City is populated just fine, however ApplicationUser is not.

Could this be a naming issue? I've already tried UserId / User and AspNetUserId / AspNetUser as property names without succes.

I'm using Migrations to create the database. The table name that gets created for users is AspNetUsers.

I'm using entity framework 7 beta 7, not sure if this applies to other versions as well.

These are the files generated by EF Migrations.

ApplicationDbContextModelSnapshot.cs

20150929181902_Init.cs

20150929181902_Init.Designer.cs

(I noticed I forgot to include the Building > City relation when generating files for upload, but that shouldn't matter for the example)


Solution

  • I've finally figured it out.

    ApplicationUser inherits from IdentityUser which inherits from IdentityUser<string>. The generic type is used as the primary key, so a string!

    I changed my Guid foreign key properties to strings and now everything is working.