ASP.NET Identity 2.1 and EF 6 - ApplicationUser relationships with other entities

点点圈 提交于 2019-11-30 23:06:16

You can specify the relationgship in OnModelCreating.

Try to use one DbContext per database. Usually you make different DbContexts for different databases, not for same.

Move all your entities in ApplicationDbContext and follow the instruction below.

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("name=MyDataModel", throwIfV1Schema: false)
    {
    }

    public DbSet<MyPortfolio> Portfolios { get; set; }
    // The rest of the entities
    // goes here

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<MyPortfolio>()
            .HasRequired(m => m.User  )
            .WithOptional(m => m.Portfolio )
            .Map(m => { m.MapKey("UserId"); });

        base.OnModelCreating(modelBuilder);

        //sql output log
        Database.Log = s => Debug.Write(s);
    }

}

Than you have to update your database, with migration, it's very easy. Open Package Manager Console in Visual Studio and enter this commands in order.

Enable-Migration
Add-Migration UserPortofolioRelation`
Update-Database
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!