如何在 EntityFramework 中将值播种到 aspnet_UsersInRoles

发布于 2024-12-25 15:06:01 字数 1179 浏览 3 评论 0原文

我目前正在创建一个结合了 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 之间建立多对多关系。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北音执念 2025-01-01 15:06:01

您需要将 Role 添加到 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”用户。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文