首先使用EF代码为数据库设置数据库时创建用户和角色

时间:2015-04-07 16:54:56

标签: c# .net linq entity-framework ef-code-first

我正在尝试为每个可以拥有List的用户提供数据库。如何在代码中添加角色列表{1,2,3}(即向每个用户添加“Admin”,“User”...的角色)(即,我使用 SelectMany func):

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));
    }

}

1 个答案:

答案 0 :(得分:0)

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();

应该这样做。