EF Code First - 播种需要外键引用的数据
我有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果在上下文中执行
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 inSeedRoles
otherwise you will create anotherRole
with the same name. You must either pass created role / roles toSeedAdministrators
(which is correct approach) or you can try to querycontext.Roles.Local.Where(r => r.Name = "...")
and search for the role.