Идентификатор события: 1026 System.InvalidOperationException в System.Linq.Enumerable.Single

Я внес следующие изменения в свой DbContext

//public DbSet<Role> Roles { get; set; }  //old
//public DbSet<TypePermissionObject> TypePermissionObjects { get; set; } //old
//public DbSet<User> Users { get; set; } //old

public DbSet<PermissionPolicyRole> Roles { get; set; }
public DbSet<PermissionPolicyTypePermissionObject> TypePermissionObjects { get; set; }
public DbSet<PermissionPolicyUser> Users { get; set; }

Теперь следующая строка кода возвращает ошибку. Когда он должен возвращать false.

var compatible = db.Database.CompatibleWithModel(false); 

Стек вызовов

Application: MyApp2.Win.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.InvalidOperationException
   at System.Linq.Enumerable.Single[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Collections.Generic.IEnumerable`1<System.__Canon>, System.Func`2<System.__Canon,Boolean>)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer+<GetStoreAssociationTypePairs>d__15.MoveNext()
   at System.Linq.Enumerable+<SelectManyIterator>d__23`3[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext()
   at System.Linq.Enumerable+<DistinctIterator>d__64`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext()
   at System.Collections.Generic.List`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]..ctor(System.Collections.Generic.IEnumerable`1<System.__Canon>)
   at System.Linq.Enumerable.ToList[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Collections.Generic.IEnumerable`1<System.__Canon>)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.FindAssociationTypePairs(System.Collections.Generic.ICollection`1<System.Tuple`2<System.Data.Entity.Core.Metadata.Edm.EntityType,System.Data.Entity.Core.Metadata.Edm.EntityType>>)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata, ModelMetadata, System.Lazy`1<System.Data.Entity.Migrations.Infrastructure.ModificationCommandTreeGenerator>, System.Data.Entity.Migrations.Sql.MigrationSqlGenerator, System.String, System.String)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(System.Xml.Linq.XDocument, System.Xml.Linq.XDocument, System.Lazy`1<System.Data.Entity.Migrations.Infrastructure.ModificationCommandTreeGenerator>, System.Data.Entity.Migrations.Sql.MigrationSqlGenerator, System.String, System.String)
   at System.Data.Entity.Internal.InternalContext.ModelMatches(System.Data.Entity.Migrations.Infrastructure.VersionedModel)
   at System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean, System.Data.Entity.Internal.DatabaseExistenceState)
   at System.Data.Entity.CreateDatabaseIfNotExists`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].InitializeDatabase(System.__Canon)
   at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(System.Action)
   at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
   at System.Data.Entity.Internal.RetryAction`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].PerformAction(System.__Canon)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(System.Action`1<System.Data.Entity.Internal.InternalContext>)
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(System.Type)
   at System.Data.Entity.Internal.Linq.InternalSet`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Count[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Linq.IQueryable`1<System.__Canon>)
   at MyApp2.Win.Program.Main()

Я дважды проверил строку подключения

Ссылка на проект EntityFramework 6.4.4

Средство просмотра событий показывает, что источником ошибки является среда выполнения.NET. Перекрестная проверка времени ошибки с выводом из Process Monitor (с sysinterenals.com) Я вижу ошибку NAME NOT FOUND для EntityFramework.pdb На 4 миллисекунды раньше возникла ошибка NAME NOT FOUND для BiDInterface

Ответ на этот вопрос указывает на то, что в моей базе данных могут быть повторяющиеся записи. Я не совсем понимаю, что имеется в виду.

Я попытался перейти на следующее, но это не помогло /

  public DbSet<PermissionPolicyRole> Roles2 { get; set; }
  public DbSet<PermissionPolicyTypePermissionObject> TypePermissionObjects2 { get; set; }
  public DbSet<PermissionPolicyUser> Users2 { get; set; }

[Обновить]

Я решил удалить миграции и создать новый. Когда я попытался это сделать, я получил следующую ошибку в консоли PM

PM> add-migration security
System.InvalidOperationException: Sequence contains no matching element
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<GetStoreAssociationTypePairs>d__15.MoveNext()
   at System.Linq.Enumerable.<SelectManyIterator>d__23`3.MoveNext()
   at System.Linq.Enumerable.<DistinctIterator>d__64`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.FindAssociationTypePairs(ICollection`1 entityTypePairs)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
   at System.Data.Entity.Migrations.DbMigrator.Scaffold(String migrationName, String namespace, Boolean ignoreChanges)
   at System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInternal(String name, DbConnectionInfo connectionInfo, String migrationsConfigurationName, Boolean ignoreChanges)
   at System.Data.Entity.Infrastructure.Design.Executor.Scaffold.<>c__DisplayClass0_0.<.ctor>b__0()
   at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.<>c__DisplayClass4_0`1.<Execute>b__0()
   at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
Sequence contains no matching element
PM> 

У меня в DbContext следующее

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Configurations.Add(new RoleConfiguration());
    modelBuilder.Configurations.Add(new UserConfiguration());
}

с участием

public class RoleConfiguration : EntityTypeConfiguration<DevExpress.Persistent.BaseImpl.EF.PermissionPolicy.PermissionPolicyRole>
{
    public RoleConfiguration()
    {
        HasMany(x => x.Users).WithMany(y => y.Roles).Map(x => x.ToTable("PermissionPolicyUserPermissionPolicyRoles"));
    }
}

public class UserConfiguration : EntityTypeConfiguration<DevExpress.Persistent.BaseImpl.EF.PermissionPolicy.PermissionPolicyUser>
{
    public UserConfiguration()
    {
        HasMany(x => x.Roles).WithMany(y => y.Users).Map(x => x.ToTable("PermissionPolicyUserPermissionPolicyRoles"));
    }
}

[Обновить]

Я изучил новый проект xaf и понял, что конфигурации не нужны.

Теперь я пытаюсь запустить миграцию без файлов конфигурации, которые я получаю.

PM> безопасность добавления-миграции

 ystem.InvalidOperationException: Sequence contains no matching element
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<GetStoreAssociationTypePairs>d__15.MoveNext()
   at System.Linq.Enumerable.<SelectManyIterator>d__23`3.MoveNext()
   at System.Linq.Enumerable.<DistinctIterator>d__64`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.FindAssociationTypePairs(ICollection`1 entityTypePairs)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
   at System.Data.Entity.Migrations.DbMigrator.Scaffold(String migrationName, String namespace, Boolean ignoreChanges)
   at System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInternal(String name, DbConnectionInfo connectionInfo, String migrationsConfigurationName, Boolean ignoreChanges)
   at System.Data.Entity.Infrastructure.Design.Executor.Scaffold.<>c__DisplayClass0_0.<.ctor>b__0()
   at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.<>c__DisplayClass4_0`1.<Execute>b__0()
   at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
Sequence contains no matching element
PM> 

1 ответ

Решение

Я думаю, что обновление таблицы безопасности выполнено в неправильном порядке.

Мне нужно будет откатиться и действовать более осторожно.

Другие вопросы по тегам