我目前正在创建一个包含EntityFramework和aspnet成员资格表的应用程序。
为了动态创建aspnet成员资格表,我遵循了本教程:http://imar.spaanjaars.com/563/using-entity-framework-code-first-and-aspnet-membership-together
我的问题是aspnet_UsersInRoles
表。为了映射表,我修改了OnModelCreating
并添加了ff代码:
modelBuilder.Entity<AspnetUser>()
.HasMany(u => u.AspnetRoles)
.WithMany(r => r.AspnetUsers)
.Map(m =>
{
m.ToTable("aspnet_UsersInRoles");
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
});
它成功创建了aspnet_UsersInRoles
表,但我的问题是我没有这个类/实体,当我覆盖Seed
方法时,我无法初始化值。 / p>
创建实体aspnet_UsersInRoles
也不起作用,因为aspnet_Users
和aspnet_Roles
之间的多对多关系会创建一个新表。
有关如何做到这一点的任何想法?使用表aspnet_Users
在aspnet_Roles
和aspnet_UsersInRoles
之间建立多对多的关系并初始化其中的值。
答案 0 :(得分:1)
您需要将Role
添加到AspnetRoles
类的AspnetUser
集合属性。
var role = new AspnetRole { Name = "Foo" };
var user = new AspnetUser { Name = "Bar", /*other props*/ };
user.AspnetRoles = new List { role };
context.Users.Add(user);
这将为“Bar”用户添加“Foo”角色。