EF Code First - 播种需要外键引用的数据

发布于 2024-11-05 15:15:06 字数 922 浏览 0 评论 0原文

我有 2 个实体 - 角色和管理员。角色有两个值 - 搜索管理员和超级管理员。我使用 EF Code First 模型创建了这些。现在我尝试将值植入数据库,并首先添加角色:

    private static void SeedRoles(PayByPhoneDbContext context)
    {
        var roles = new List<Role> {new Role {Name = "Search Administrator"}, new Role {Name = "Super Administrator"}};
        roles.ForEach(role => context.Roles.Add(role));
    }

现在我想使用上面创建的角色之一在添加管理员时使用:

    private void SeedAdministrators(PayByPhoneDbContext context)
    {
        var administrators = new List<Administrator>{new Administrator {Email = "[email protected]", Name = "Achinth Gurkhi", Password = "hello", Active = true, Role = ? }}
    }

如何在此处设置角色?我应该说 Role = new Role { Name = "Super Administrator" } 还是搜索由 SeedRoles 方法插入的角色?另外,如何使用上下文搜索现有角色?

I have 2 entities - Roles and Administrators. Roles has two values - Search Admin and Super Admin. I have created these using EF Code First model. Now I am trying to seed values to the database and I add the roles first:

    private static void SeedRoles(PayByPhoneDbContext context)
    {
        var roles = new List<Role> {new Role {Name = "Search Administrator"}, new Role {Name = "Super Administrator"}};
        roles.ForEach(role => context.Roles.Add(role));
    }

Now I want to use one of the roles created above to be used while adding administrators:

    private void SeedAdministrators(PayByPhoneDbContext context)
    {
        var administrators = new List<Administrator>{new Administrator {Email = "[email protected]", Name = "Achinth Gurkhi", Password = "hello", Active = true, Role = ? }}
    }

How do I set Role here? Should I say Role = new Role { Name = "Super Administrator" } or search for Role inserted by SeedRoles method? Also, how do I search for an existing role using the context?

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

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

发布评论

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

评论(1

苏佲洛 2024-11-12 15:15:06

如果在上下文中执行 SaveChanges 之前调用这两个方法,则必须使用在 SeedRoles 中创建的相同角色实例,否则您将创建另一个 Role同名。您必须将创建的角色传递给 SeedAdministrators (这是正确的方法),或者您可以尝试查询 context.Roles.Local.Where(r => r.Name = ". ..") 并搜索角色。

If both methods are called before you execute SaveChanges on your context you must use the same role instance you created in SeedRoles otherwise you will create another Role with the same name. You must either pass created role / roles to SeedAdministrators (which is correct approach) or you can try to query context.Roles.Local.Where(r => r.Name = "...") and search for the role.

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