How to Seed value to aspnet_UsersInRoles in EntityFramework

700 views Asked by At

I'm currently creating an application with EntityFramework and aspnet membership tables combined.

To create the aspnet membership tables dynamically, I followed this tutorial: http://imar.spaanjaars.com/563/using-entity-framework-code-first-and-aspnet-membership-together

My problem is the aspnet_UsersInRoles table. To map the table I modified OnModelCreating and add the ff code:

modelBuilder.Entity<AspnetUser>()
                .HasMany(u => u.AspnetRoles)
                .WithMany(r => r.AspnetUsers)
                .Map(m =>
                    {
                        m.ToTable("aspnet_UsersInRoles");
                        m.MapLeftKey("UserId");
                        m.MapRightKey("RoleId");
                    });

It created successfully the aspnet_UsersInRoles table, but my problem is that I don't have a class/entity for this and I'm unable to initialize value when I override the Seed method.

Creating an entity aspnet_UsersInRoles also doesn't work because the many-to-many relationship between aspnet_Users and aspnet_Roles create a new table.

Any idea on how to do this? Having many to many relationship between aspnet_Users and aspnet_Roles using the table aspnet_UsersInRoles and initializing values in it.

1

There are 1 answers

0
Eranga On BEST ANSWER

You need to add the Roles to AspnetRoles collection property of the AspnetUser class.

var role = new AspnetRole { Name = "Foo" };
var user = new AspnetUser { Name = "Bar", /*other props*/ };

user.AspnetRoles = new List { role };

context.Users.Add(user);

This will add "Foo" role to the "Bar" user.