C# 在首先使用EF代码设定数据库种子的同时创建用户和角色

C# 在首先使用EF代码设定数据库种子的同时创建用户和角色,c#,.net,linq,entity-framework,ef-code-first,C#,.net,Linq,Entity Framework,Ef Code First,我正在尝试种子数据库的用户,其中每一个都可以有列表。如何在代码中添加角色列表{1,2,3}(即向每个用户添加“管理员”、“用户”…的角色)(即使用SelectManyfunc): 公共类角色 { 公共角色(字符串角色名,int角色类型) { this.RoleName=RoleName; this.RoleType=RoleType; } [关键] public int RoleId{get;set;} 公共字符串RoleName{get;set;} 公共int角色类型{get;set;} }

我正在尝试种子数据库的用户,其中每一个都可以有列表。如何在代码中添加角色列表{1,2,3}(即向每个用户添加“管理员”、“用户”…的角色)(即使用SelectManyfunc):

公共类角色
{
公共角色(字符串角色名,int角色类型)
{
this.RoleName=RoleName;
this.RoleType=RoleType;
}
[关键]
public int RoleId{get;set;}
公共字符串RoleName{get;set;}
公共int角色类型{get;set;}
}
公共类用户
{
[关键]
public int UserId{get;set;}
公共字符串名称{get;set;}
公共整数{get;set;}
公共虚拟ICollection角色{get;set;}
公共重写字符串ToString()
{
返回string.Format(“[User UserId={0},Name={1},Age={2},RolesCount={3}]”,UserId,Name,Age,Roles.Count);
}
}
公共类UserContext:DbContext
{
公共数据库集角色{get;set;}
公共数据库集用户{get;set;}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
//modelBuilder.Entity().HasMany(u=>u.Roles)。WithMany(r=>r.Users)
//.Map(m=>m.MapLeftKey(“UserId”).MapRightKey(“RoleId”)
//.ToTable(“用户角色”);
SetInitializer(新的ContextInitializer());
}
}
公共类上下文初始化器:DropCreateDatabaseAlways
{
受保护的覆盖无效种子(UserContext上下文)
{
CreateRole(“管理员”,1,上下文);
CreateRole(“超级用户”,2,上下文);
CreateRole(“用户”,3,上下文);
CreateUser(“Vovan Super”,31,context.Roles.SelectMany(r=>r,(role,user)=>newlist(role));
context.Users.ForEachAsync(Console.WriteLine);
种子(上下文);
}
私有void CreateUser(字符串名称、整数年龄、列表角色、UserContext ctx)
{
添加(新用户{Name=Name,Age=Age,Roles=Roles});
}
私有void CreateRole(字符串roleName、int roleType、UserContext ctx)
{
添加(新角色(roleName,roleType));
}
}
var角色=新列表()
{
新角色(“管理员”,1),
新角色(“超级用户”,2),
新角色(“用户”,1)
};
ctx.Roles.AddRange(角色);
添加(新用户{Name=“Vovan Super”,年龄=31,角色=Roles});
ctx.SaveChanges();

应该这样做。

因此,您不希望
foreach
遍历用户列表,并向每个用户添加
User
Admin
角色,对吗?在seed中,我创建了3个角色,并希望将其中一些角色分配给一些用户(即用户拥有角色列表);因此,在前3行种子角色被设置为上下文中,我想将(所有3个角色)添加到我正在创建的新用户(实际上主要是关于在范围内使用SelectMany func和其他人们可以提供的优雅解决方案的问题:)删除模板文本OK,它是:)但您对所述工作流的想法是什么,我,e:我们将角色集添加到DbContext,并立即从中提取它们添加到用户,就像我尝试使用SelectMany一样;基本上,这更多的是关于LINQ的问题,以及使用它的好技术(尤其是我发现最难理解的许多函数),因为您使用的是DropCreateAllways策略,我不明白为什么您需要查询您已经拥有了所有可用的角色,如果我不需要将所有角色分配给所有用户,我只需编写一个where查询来选择角色的子集,因为您使用的是角色类型(我假设这是唯一的),所以最好根据它进行查询。我认为context.Roles.SelectMany应该是context.Roles.Local.SelectMany,第一个查询数据库,第二个查询尚未提交到db的本地更改
public class Role
{
    public Role(string roleName, int roleType)
    {
        this.RoleName = roleName;
        this.RoleType = roleType;

    }
    [Key]
    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public int RoleType { get; set; }

}
public class User
{
    [Key]        
    public int UserId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public virtual ICollection<Role> Roles { get; set; }

    public override string ToString()
    {
        return string.Format("[User UserId={0}, Name={1}, Age={2},    RolesCount={3}]", UserId, Name, Age, Roles.Count);
    }

}

public class UserContext : DbContext
{
    public DbSet<Role> Roles { get; set; }
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      //            modelBuilder.Entity<User>().HasMany(u => u.Roles).WithMany(r => r.Users)
      //                .Map(m => m.MapLeftKey("UserId").MapRightKey("RoleId")
      //                     .ToTable("UserRole"));
        Database.SetInitializer(new ContextInitialiser()) ;
    }


}

public class ContextInitialiser: DropCreateDatabaseAlways<UserContext>
{
    protected override void Seed(UserContext context)
    {
        CreateRole("Admin", 1, context);
        CreateRole("SuperUser", 2, context);
        CreateRole("User", 3, context);
        CreateUser("Vovan Super", 31, context.Roles.SelectMany(r => r, (role, user) => new List<Role> (role) ));
        context.Users.ForEachAsync(  Console.WriteLine );
        base.Seed(context);         
    }

    private void CreateUser(string name, int age, List<Role> roles, UserContext ctx)
    {
        ctx.Users.Add(new User {Name = name, Age = age, Roles = roles }  );
    }
    private void CreateRole(string roleName, int roleType, UserContext ctx)
    {
        ctx.Roles.Add(new Role(roleName, roleType));
    }

}
var roles = new List<Role>()
{
new Role("Admin", 1),
new Role("SuperUser", 2),
new Role("User", 1)
};
ctx.Roles.AddRange(roles);
ctx.Users.Add(new User {Name = "Vovan Super", Age = 31, Roles = roles }  );
ctx.SaveChanges();