Map tables using fluent api in asp.net MVC5 EF6?

为君一笑 提交于 2019-11-29 06:04:53

Calling base.OnModelCreating(modelBuilder) did not solve the issue for me.

The behavior of Microsoft.AspNet.Identity.EntityFramework seems to be different in VS2013-Preview, VS2013-RC, and VS2013-RTM. I'm using the RTM version.

After inheriting from IdentityUser I had to recreate all other primary keys in the model to make it work:

public class ApplicationUser : IdentityUser
{
    public string DisplayName { get; set; }
}


public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext() : base("DefaultConnection") { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
        modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
        modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
    }

(See Configuring/Mapping Properties and Types with the Fluent API)

I guess work on AspNet.Identity.EntityFramework is ongoing and this will be fixed (?)

Call base.OnModelCreating(modelBuilder) after configuration added.

Follow these steps around OnModelCreating method and test after each one to be aware of taking effect:

  1. Make sure you have one Context to prevent of their rule conflicts.
  2. Call base.OnModelCreating(modelBuilder); inside the mentioned method (first of all)
  3. Add the followings plus previews step in the method:


modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!