2

Я пытаюсь разделить пользователей и роли в моей базе данных. В настоящее время используется Code First Entity Framework с автоматическими переходами в C# MVC4. Всякий раз, когда я называюНевозможно посеять пользователей и роли

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, Seed() и не удалось создать файл _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 даже не бежится - Я могу разместить более одного в методе Seed, а не получать t он может быть вызван только однажды "ошибкой, которую вы обычно получите.

Мой метод семени находится в моем доменном проекте вместе со всеми моделями, в то время как все остальное находится в проекте WebUI. Не уверен, что это имеет к этому какое-то отношение.

ответ

0

Удалить существующую ссылку на WebMatrix.WebData Добавить ссылку WebMatrix.WebData версии 2. Ошибки остановится.

+0

как ссылаться на WebMatrix. WebData версия 2, пожалуйста? – ABCmo

+0

вы можете добавить это в web.config <компиляции отлаживать = "истина" targetFramework = "4,5"> <добавить сборку = "WebMatrix.Data, Version = 2.0.0.0, культура = нейтральной, PublicKeyToken = 31bf3856ad364e35" /> TheSM

4

Просто положить, что ленивый инициализации в верхней части метода Seed

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

Интересно, что не может найти WebSecurity.Initialized в методе Seed - Ошибка «WebMatrix.WebData.WebSecurity» не содержит определение для «инициализирован» – TryCatch

+1

я ссылке на старую версию WebMatrix.WebData в проект моего домена. Я ссылаюсь на v2, добавил ваш код, и теперь он работает. – TryCatch

+0

+1 для if (! WebSecurity.Initialized). Метод My Seed() вызывается дважды! Странно кажется, что второй вызов запускается из самого тела самого метода 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» (вам не хватает ссылки на сборку?) – TryCatch

Смежные вопросы