【问题标题】:How to Seed value to aspnet_UsersInRoles in EntityFramework如何在实体框架中为 aspnetUserRoles 播种值
【发布时间】:2012-01-09 01:23:49
【问题描述】:

我目前正在创建一个结合了 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 方法时我无法初始化值。

创建实体aspnet_UsersInRoles 也不起作用,因为aspnet_Usersaspnet_Roles 之间的多对多关系会创建一个新表。

知道如何做到这一点吗?使用表 aspnet_UsersInRoles 并在其中初始化值,在 aspnet_Usersaspnet_Roles 之间建立多对多关系。

【问题讨论】:

    标签: entity-framework-4 entity-framework-4.1 ef-code-first aspnetdb


    【解决方案1】:

    您需要将Roles 添加到AspnetUser 类的AspnetRoles 集合属性中。

    var role = new AspnetRole { Name = "Foo" };
    var user = new AspnetUser { Name = "Bar", /*other props*/ };
    
    user.AspnetRoles = new List { role };
    
    context.Users.Add(user);
    

    这会将“Foo”角色添加到“Bar”用户。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多