2012-11-26 45 views
2

我想將用戶和角色種入我的數據庫。 目前在C#MVC4中使用帶有自動遷移的Code First Entity Framework。 每當我打電話無法種子的用戶和角色

Update-Database -Force

我得到以下錯誤:

Running Seed method. System.InvalidOperationException: You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in the root of your site. at WebMatrix.WebData.SimpleRoleProvider.get_PreviousProvider() at WebMatrix.WebData.SimpleRoleProvider.RoleExists(String roleName) at System.Web.Security.Roles.RoleExists(String roleName) at GratifyGaming.Domain.Migrations.Configuration.Seed(GratifyGamingContext context) in C:\Users\Unreal\Documents\Visual Studio 2010\Projects\GratifyGaming\GratifyGaming.Domain\Migrations\Configuration.cs:line 36 at System.Data.Entity.Migrations.DbMigrationsConfiguration 1.OnSeed(DbContext context) at System.Data.Entity.Migrations.DbMigrator.SeedDatabase() at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase() at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable 1 pendingMigrations, String targetMigrationId, String lastMigrationId) at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId) at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration) at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore() at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run() You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in the root of your site.

問題的代碼行是Role.Exists

我試圖把WebSecurity.InitializeDatabaseConnection在Global.asax中,種子(),並創建了一個沒有成功的_AppStart.cshtml。我瀏覽了互聯網尋找可能的解決方案,並沒有一個工作(包括其他堆棧溢出文章)。下面有一些值得注意的博客文章。

見代碼。

[Configuration.cs]

protected override void Seed(GratifyGaming.Domain.Models.DAL.GratifyGamingContext context) 
    { 
     var criteria = new List<Criterion> 
     { 
      new Criterion { ID = 1, IsMandatory=true, Name = "Gameplay", Description="The playability of the games core mechanics" }, 
      new Criterion { ID = 2, IsMandatory=true, Name = "Art Style", Description="The artistic feel of the game as a whole. Elements such as story, style and originality come into play." }, 
      new Criterion { ID = 3, IsMandatory=true, Name = "Longevity", Description="How long did this game keep you entertained?" }, 
      new Criterion { ID = 4, IsMandatory=true, Name = "Graphics", Description="How good does the game look?" } 
     }; 

     criteria.ForEach(s => context.Criterion.AddOrUpdate(s)); 
     context.SaveChanges(); 


     if (!Roles.RoleExists("Administrator")) 
      Roles.CreateRole("Administrator"); 

     if (!WebSecurity.UserExists("user")) 
      WebSecurity.CreateUserAndAccount(
       "user", 
       "password"); 

     if (!Roles.GetRolesForUser("lelong37").Contains("Administrator")) 
      Roles.AddUsersToRoles(new[] { "user" }, new[] { "Administrator" }); 
    } 

判據種子代碼工作而不會失敗。

[_AppStart.cshtml]

@{ 
if (!WebSecurity.Initialized) 
{ 
    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", 
              "UserName", autoCreateTables: true); 
} 
} 

正常登錄到我的網站與這個設在這裏完美的作品。

[web.config文件]

<roleManager enabled="true" defaultProvider="SimpleRoleProvider"> 
    <providers> 
    <clear/> 
    <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/> 
    </providers> 
</roleManager> 
<membership defaultProvider="SimpleMembershipProvider"> 
    <providers> 
    <clear/> 
    <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" /> 
    </providers> 
</membership> 

[AccountModel.cs]

[Table("UserProfile")] 
public class UserProfile 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int UserId { get; set; } 
    public string UserName { get; set; } 
    public string Email { get; set; } 
    public virtual ICollection<Game> AttachedGames { get; set; } 

    public virtual ICollection<UserGratificationRecord> GratificationHistory { get; set; } 

    [ForeignKey("UserLevel")] 
    public int? AcheivementID { get; set; } 
    public virtual Acheivement UserLevel { get; set; } 

    public int? NumOfGratifictions { get; set; } 

} 

UPDATE

我覺得WebSecurity.InitializeDatabaseConnection甚至沒有正在運行 - 我可以在我的種子方法中放置多個,但不能獲得t他'只能被調用一次'錯誤,你通常會得到。

我的種子方法是在我的域項目中的所有模型,而其他一切都在WebUI項目中。不知道這與它有什麼關係。

回答

0

刪除您現有的參考WebMatrix.WebData 添加引用WebMatrix.WebData版本2. 錯誤將停止。

+0

如何引用WebMatrix。 WebData版本2請? – ABCmo

+0

你可以添加這web.config文件 <編譯調試= 「真」 targetFramework = 「4.5」> <添加組​​件= 「WebMatrix.Data,版本= 2.0.0.0,文化=中性公鑰= 31bf3856ad364e35」 /> TheSM

4

只要把該延遲初始化到您的種子法

protected override void Seed(GratifyGaming.Domain.Models.DAL.GratifyGamingContext context) 
{ 
    if (!WebSecurity.Initialized) 
    { 
     WebSecurity.InitializeDatabaseConnection("DefaultConnection", 
               "UserProfile", 
               "UserId", 
               "UserName", 
               autoCreateTables: true); 
    } 
+0

有趣的是它不能在種子法找到WebSecurity.Initialized - 錯誤「WebMatrix.WebData.WebSecurity」不包含「初始化」 – TryCatch

+1

定義我在引用WebMatrix.WebData的舊版本我的域名項目。我參考v2,添加了你的代碼,現在它工作。對於if(!WebSecurity.Initialized),爲 – TryCatch

+0

+1。我的種子()方法被調用兩次!奇怪的是,第二個調用看起來是從Seed方法本身內部觸發的(即從一行代碼中,我訪問在遷移過程中新創建的一個DbSets)。沒有WebSecurity.Initialized檢查第二個Seed()調用導致「WebSecurity.InitializeDatabaseConnection」方法只能調用一次。「 – Ilan

1

的頂部在你App_Start,試着加入:

 var configuration = new Data.Migrations.Configuration(); 
     var migrator = new DbMigrator(configuration); 
     migrator.Update(); 

你必須使你的配置。CS文件公開

public class Configuration : DbMigrationsConfigurati 

這應該使你的後裔方法被調用,當你運行你的程序

+0

感謝您的輸入TMan。添加您建議的代碼會產生以下錯誤: 錯誤命名空間'WebMatrix.Data'中不存在類型或名稱空間名稱'Migrations'(缺少程序集引用?) – TryCatch