title: ASP.NET Identity 2.1 and EF 6 - ApplicationUser relationships with other entities
body: <p>Can't seem to find an answer to this one, even though what I'm doing seems like it would be common and important to most developers. In most systems with user accounts, the user table is tied to other tables in the database. That's all I want. I'm using MSSQL Express 2012 and VS 2013.</p>
  
  <p>I have a class library where I'm using the code-first approach to generate tables. I moved the IdentityModel class from the MVC project to this class library as well. Everything works separately - my tables are generated and work fine, and the Identity tables are generated when I register a new user.</p>
  
  <p>However, now I need one of my entities/tables tied to the ApplicationUser in a 1-1 relationship, but adding the field like so prevents the Identity tables from being generated:</p>
  
  <pre><code>public class ApplicationUser : IdentityUser
  {
      //***custom field
      public MyPortfolio Portfolio { get; set; }
  
      public async Task&lt;ClaimsIdentity&gt; GenerateUserIdentityAsync(UserManager&lt;ApplicationUser&gt; manager)
      {
          var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
          return userIdentity;
      }
  }
  
  public class ApplicationDbContext : IdentityDbContext&lt;ApplicationUser&gt;
  {
      public ApplicationDbContext()
          : base("name=MyDataModel", throwIfV1Schema: false)
      {
      }
  
      public static ApplicationDbContext Create()
      {
          return new ApplicationDbContext();
      }
  
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.Conventions.Remove&lt;PluralizingTableNameConvention&gt;();
  
          base.OnModelCreating(modelBuilder);
  
          //sql output log
          Database.Log = s =&gt; Debug.Write(s);
      }
  }
  </code></pre>
  
  <p>..."MyPortfolio" is just plain entity:</p>
  
  <pre><code>    public class MyPortfolio
      {
          [Key]
          [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
          public int Id { get; set; }
  
          [StringLength(45, MinimumLength = 3)]
          public string Name { get; set; }
  
          public Boolean IsMaster { get; set; }
  
          //public ApplicationUser User { get; set; } //threw exception!
      }
  </code></pre>
  
  <p>I don't know too much about Identity, but have read that Migrations might be the answer. I'd rather avoid any further complexity if possible. Will that really be necessary? I am in early development and will be dropping/re-creating the tables many more times.</p>
  
  <p><strong>UPDATE 1:</strong></p>
  
  <p>OK, I added everything like adricadar described below. Here's what happened...</p>
  
  <p>When adding migrations I had to select my class library from the "Default project" dropdown in the Package Manager Console. When doing Enable-Migrations, I got the following error:</p>
  
  <blockquote>
    <p>More than one context type was found in the assembly 'MyProject.Data'.
    To enable migrations for 'MyProject.Models.ApplicationDbContext', use
    Enable-Migrations -ContextTypeName
    MyProject.Models.ApplicationDbContext. To enable migrations for
    'MyProject.Data.MyDataModel', use Enable-Migrations -ContextTypeName
    MyProject.Data.MyDataModel.</p>
  </blockquote>
  
  <p>...so I did the following:</p>
  
  <blockquote>
    <p>Enable-Migrations -ContextTypeName
    MyProject.Models.ApplicationDbContext</p>
  </blockquote>
  
  <p>...which as expected, created the Configuration class and an "InitialCreate" class for the AspNetUser* tables.</p>
  
  <p>I then ran "Add-Migration UserPortofolioRelation", which generated the DbMigration class with Up() and Down(). Up and Down both define all of the tables I've defined in MyDataModel. I now see the relationship between MyPortfolio and AspNetUsers in Up():</p>
  
  <pre><code>        CreateTable(
                  "dbo.MyPortfolio",
                  c =&gt; new
                          {
                              Id = c.Int(nullable: false, identity: true),
                              Name = c.String(maxLength: 45),
                              IsMaster = c.Boolean(nullable: false),
                              UserId = c.String(nullable: false, maxLength: 128),
                          })
                  .PrimaryKey(t =&gt; t.Id)
                  .ForeignKey("dbo.AspNetUsers", t =&gt; t.UserId)
                  .Index(t =&gt; t.UserId);
  </code></pre>
  
  <p>When I run Update-Database, I get the following error:</p>
  
  <blockquote>
    <p>Applying explicit migrations:
    [201504141316068_UserPortofolioRelation]. Applying explicit migration:
    201504141316068_UserPortofolioRelation.
    System.Data.SqlClient.SqlException (0x80131904): There is already an
    object named 'MyPortfolio' in the database.</p>
  </blockquote>
  
  <p>The extent of my knowledge of Migrations is this basic tutorial:</p>
  
  <p><a href="https://msdn.microsoft.com/en-us/data/jj591621.aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/data/jj591621.aspx</a></p>
  
  <p>This worked for me, and only the new fields were defined in the generated migrations code, not commands to drop and create all the tables.</p>
  
  <p><strong>UPDATE 2:</strong></p>
  
  <p>I followed this tutorial, which seemed to explain things a little more clearly when trying to work with migrations on multiple data contexts:</p>
  
  <p><a href="http://www.dotnet-tricks.com/Tutorial/entityframework/2VOa140214-Entity-Framework-6-Code-First-Migrations-with-Multiple-Data-Contexts.html" rel="nofollow noreferrer">http://www.dotnet-tricks.com/Tutorial/entityframework/2VOa140214-Entity-Framework-6-Code-First-Migrations-with-Multiple-Data-Contexts.html</a></p>
  
  <p>I ran this command:</p>
  
  <blockquote>
    <p>Enable-Migrations -ContextTypeName
    MyProject.Models.ApplicationDbContext</p>
  </blockquote>
  
  <p>The following Configuration was created:</p>
  
  <pre><code>internal sealed class Configuration : DbMigrationsConfiguration&lt;MyProject.Models.ApplicationDbContext&gt;
  {
      public Configuration()
      {
          AutomaticMigrationsEnabled = false;
      }
  
      protected override void Seed(MyProject.Models.ApplicationDbContext context)
      {
      }
  }
  </code></pre>
  
  <p>...looking good. Then I ran this:</p>
  
  <blockquote>
    <p>Add-Migration -Configuration MyProject.Data.Migrations.Configuration
    MigrationIdentity</p>
  </blockquote>
  
  <p>...which generated this file:</p>
  
  <pre><code>namespace MyProject.Data.Migrations
  {
      using System;
      using System.Data.Entity.Migrations;
  
      public partial class MigrationIdentity : DbMigration
      {
          public override void Up()
          {
              CreateTable(
                      "dbo.MyPortfolio",
                      c =&gt; new
                              {
                                  Id = c.Int(nullable: false, identity: true),
                                  Name = c.String(maxLength: 45),
                                  IsMaster = c.Boolean(nullable: false),
                                  UserId = c.String(nullable: false, maxLength: 128),
                              })
                      .PrimaryKey(t =&gt; t.Id)
                      .ForeignKey("dbo.AspNetUsers", t =&gt; t.UserId)
                      .Index(t =&gt; t.UserId);
  
              ...my other non-identity entities...
  
              CreateTable(
                      "dbo.AspNetUsers",
                      c =&gt; new
                              {
                                  Id = c.String(nullable: false, maxLength: 128),
                                  Email = c.String(maxLength: 256),
                                  EmailConfirmed = c.Boolean(nullable: false),
                                  PasswordHash = c.String(),
                                  SecurityStamp = c.String(),
                                  PhoneNumber = c.String(),
                                  PhoneNumberConfirmed = c.Boolean(nullable: false),
                                  TwoFactorEnabled = c.Boolean(nullable: false),
                                  LockoutEndDateUtc = c.DateTime(),
                                  LockoutEnabled = c.Boolean(nullable: false),
                                  AccessFailedCount = c.Int(nullable: false),
                                  UserName = c.String(nullable: false, maxLength: 256),
                              })
                      .PrimaryKey(t =&gt; t.Id)
                      .Index(t =&gt; t.UserName, unique: true, name: "UserNameIndex");
  
              ...other Identity entities/tables...
  
          }
  
          public override void Down()
          {
              ...everything you'd expect...
          }
      }
  }
  </code></pre>
  
  <p>Awesome! All tables/entities in one file! So I ran it:</p>
  
  <blockquote>
    <p>Update-Database -Configuration MyProject.Data.Migrations.Configuration
    -Verbose</p>
  </blockquote>
  
  <p>...and bam! It generated all the tables with the UserId FK on the MyPortfolio table. All seems to be great with the world. Nothing can stop me now! Then I ran it and got this exception:</p>
  
  <blockquote>
    <p>One or more validation errors were detected during model generation:</p>
    
    <p>System.Data.Entity.ModelConfiguration.ModelValidationException</p>
    
    <p>MyProject.Data.IdentityUserLogin: : EntityType 'IdentityUserLogin' has
    no key defined. Define the key for this EntityType.
    MyProject.Data.IdentityUserRole: : EntityType 'IdentityUserRole' has
    no key defined. Define the key for this EntityType.
    IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is
    based on type 'IdentityUserLogin' that has no keys defined.
    IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based
    on type 'IdentityUserRole' that has no keys defined.</p>
  </blockquote>
  
  <p>A quick Google brought me back to Stack Exchange, naturally: <a href="https://stackoverflow.com/questions/28531201/entitytype-identityuserlogin-has-no-key-defined-define-the-key-for-this-entit">EntityType &#39;IdentityUserLogin&#39; has no key defined. Define the key for this EntityType</a></p>
  
  <p>The accepted answer outlines a whole slew of new possible angles to play, to try and get this to work right. This brings me back to my original question. Can I do this <em>without</em> migrations. Is that possible, in any way? With the level of complexity this comes with, I'm seriously debating "rolling my own" authentication, if not. I've already spent an exorbitant amount of time trying to simply tie a code-first entity to the Identity user. Each new door presents two more to go through. It just doesn't seem worth it...but maybe they'll clean this up a bit in the next release.</p>