我正在尝试将用户和角色植入数据库。目前在C#MVC4中使用带有自动迁移的代码优先实体框架。每当我打
更新数据库-强制
我得到以下错误:
正在运行种子方法。System.InvalidOperationException:必须调用"WebSecurity.InitializeDatabaseConnection"方法,然后再调用"WebSecurity"类的其他方法。此呼叫应置于网站根目录中的_AppStart.cshtml文件。位于WebMatrix.WebData.SimpleRoleProvider.get_PreviousProvider()位于WebMatrix.WebData.SimpleRoleProvider.RoleExists(字符串角色名称)位于System.Web.Security.Roles.RoleExists(字符串roleName)位于GratifyGaming.Domain.Migrations.Configuration.Seed(GratifyGamengContext上下文)在C:\Users\Unreal\Documents\Visual Studio中2010\Projects\GratifyGaming\GraifyGaming.Domain\Migrations\Configuration.cs:line36位于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
1pendingMigrations,字符串targetMigrationId,字符串lastMigrationId)位于System.Data.Entity.Migrations.Infrastructure.MigrateLoggingDecorator.Update(IEnumerable`1pendingMigrations,字符串targetMigrationId,字符串lastMigrationId)位于System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)位于System.Data.Entity.Migrations.Infrastructure.MigorBase.Update(字符串targetMigration)位于System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()位于System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()在调用"WebSecurity"类的任何其他方法之前,必须调用"WebSSecurity.InitializeDatabaseConnection"方法。此调用应放在的根目录中的_AppStart.cshtml文件中您的网站。
有问题的代码行是Role.Exists
我曾尝试将WebSecurity.InitializeDatabaseConnection放在Global.asax、Seed()中,并创建了_AppStart.cshtml,但没有成功。我在互联网上搜索了一个可能的解决方案,但都没有成功(包括其他堆栈溢出的文章)。下面是一些值得注意的博客文章。
- http://blog.longle.net/2012/09/25/seeding-users-and-roles-with-mvc4-simplemembershipprovider-simpleroleprovider-ef5-codefirst-and-custom-user-properties/
- http://odetocode.com/Blogs/scott/archive/2012/08/31/seeding-membership-amp-roles-in-asp-net-mvc-4.aspx
请参阅下面的代码。
[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" });
}
Criterion种子代码可以正常工作。
[AppStart.cs.html]
@{
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; }
}
更新
我认为WebSecurity.InitializeDatabaseConnection甚至没有运行——我可以在我的Seed方法中放置多个,而不会得到通常会得到的"只能调用一次"错误。
我的种子方法和所有模型都在我的域项目中,而其他所有方法都在WebUI项目中。不确定这是否与此有关。
只需将惰性init放入种子方法的顶部
protected override void Seed(GratifyGaming.Domain.Models.DAL.GratifyGamingContext context)
{
if (!WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"UserProfile",
"UserId",
"UserName",
autoCreateTables: true);
}
在应用程序启动中,尝试添加:
var configuration = new Data.Migrations.Configuration();
var migrator = new DbMigrator(configuration);
migrator.Update();
您必须将您的configuration.cs文件公开为
public class Configuration : DbMigrationsConfigurati
这应该使您的种子方法在运行程序时被调用
删除对WebMatrix.WebData的现有引用添加参考WebMatrix.WebData版本2。错误将停止。