检查迁移期间是否有记录

时间:2016-03-25 07:01:53

标签: c# sql asp.net ef-migrations

我想创建一个迁移,创建一个具有特定角色的管理员用户。我想要包含一个断言来检查该角色是否确实存在,并且没有该角色的现有用户,但显然System.Data.Entity.Migrations.DbMigration中没有用于插入记录,选择记录或获取任何反馈的方法。即使DbMigration.Sql返回void。

到目前为止,我发现进行此迁移的唯一方法是将其全部写入一个大的 .sql 文件中。

1 个答案:

答案 0 :(得分:1)

您应该在Seed类内的Configuration方法中执行此操作,而不是为此创建空白迁移。

示例(自行纠正!)

//checking is role exists
var roleExist = context.Roles.Any(x => x.Name == "MyRole");

//no existing users with that role
var withRoles = context.User2Roles.Any(x => x.Role.Name == "MyRole");

//Add or update admin user
context.Users.AddOrUpdate(x => x.Email, new User { EMail = "Admin" });

//get admin and role after creating them, if it needed(code not presented)
var role = context.Roles.Where(x => x.Name == "MyRole").First();
var admin = context.Users.Where(x => x.Email == "Admin").First();

//add role to admin if role not already was linked to him, checking code not presented
context.User2Roles.Add(new User2Roles{ User = admin, Role = role });
context.SaveChanges();