Friday, December 25, 2015

mvc code first add foreign key referencing Asp.Net Identity ApplicationUser

in my case I have my own dbcontext called MyContext.

1. in the child class MyModel add:

public ApplicationUser User { get; set; }

2. in IdentityModels add below into class ApplicationDbContext

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasRequired(MyModel => MyModel.User);
            base.OnModelCreating(modelBuilder);
        }

3. for some reason this is not enough, the same code in 2. needs to be add into my own dbcontext too. So in MyContext add below

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasRequired(MyModel => MyModel.User);
            base.OnModelCreating(modelBuilder);
        }

in database it correctly generates the foreign key relationship as:

CONSTRAINT [FK_dbo.UserProfiles_dbo.AspNetUsers_User_Id] FOREIGN KEY ([User_Id]) REFERENCES [dbo].[AspNetUsers] ([Id])

No comments: