title: Custom ASPNET Identity one to many relationship using multiple context application
body: <p>Basically, I want to have a user that can create their own stories.</p>
  
  <p>I have these classes:</p>
  
  <pre><code>public class ApplicationUser : IdentityUser
  {
    public string DisplayedName { get; set; }
  }
  
  public class Story
  {
    public int Id { get; set; }
    public string Content { get; set; }
  }
  </code></pre>
  
  <p>They are managed on a different context and so as their migration. Something like this.</p>
  
  <pre><code>public class MyDbContext : DbContext
  {
    public DbSet&lt;Story&gt; Stories { get; set; }
  }
  
  public class IdentityContext : IdentityDbContext&lt;ApplicationUser&gt;
  {
  }
  </code></pre>
  
  <p>When I try to add a migration then update them individually, it works fine but when I try to add a collection of stories in my application user.</p>
  
  <pre><code>public class ApplicationUser : IdentityUser
  {
    public string DisplayedName { get; set; }
    public virtual ICollection&lt;Story&gt; Stories { get; set; }
  }
  
  public class Story
  {
    public int Id { get; set; }
    public string Content { get; set; }
    public string WrittenById { get; set; }
    public virtual ApplicationUser WrittenBy { get; set; }
  }
  
  public class StoryMap : EntityTypeConfiguration&lt;Story&gt;
  {
    public StoryMap()
    {
      HasOptional(s =&gt; s.WrittenBy)
        .WithMany(s =&gt; s.Stories)
        .HasForeignKey(s =&gt; s.WrittenById)
        .WillCascadeOnDelete(false);
    }
  }
  </code></pre>
  
  <p>Then do a migration on my <code>Story</code> entity using the contenxt of <code>MyDbContext</code> it fails saying.</p>
  
  <pre><code>Data.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
  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.
  </code></pre>
  
  <p>But when I try the other way around in which I'll do a migration using the <code>IdentityContext</code> it would create a new table of <code>Story</code></p>
  
  <p>For now, what works is merging my contexts. Something like.</p>
  
  <pre><code>public class MyDbContext : IdentityDbContext&lt;ApplicationUser&gt;
  {
    public DbSet&lt;Story&gt; Stories { get; set; }
  }
  </code></pre>
  
  <p>But there must be a way of managing them separately, right? Or am I doing it all wrong?</p>