2012-11-26 46 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