2016-03-25 47 views
1

我想創建一個遷移,以創建具有特定角色的管理員用戶。我想包含一個斷言來檢查該角色是否真實存在,並且沒有現有用戶具有該角色,但顯然System.Data.Entity.Migrations.DbMigration中沒有插入記錄,選擇記錄或獲取任何反饋的方法。即使DbMigration.Sql也會返回void。檢查遷移過程中是否有記錄

到目前爲止,我看到使這種遷移的唯一方法是將它寫在一個大的文件.sql中。

+0

這是使用ASP.NET身份?在這種情況下,您將需要一個UserManager和RoleManager。 –

回答

1

您應該在Configuration類的Seed方法中執行此操作,而不要爲此創建空白遷移。

例(你自己更正!)

//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();