Первая модель с существующей БД. Новая БД всегда пытается создаться. Результат: «Разрешение CREATE TABLE запрещено в базе данных»

Я создал первую диаграмму модели, указывающую на пару представлений существующей БД. Когда я пытаюсь запросить указанную БД, EF пытается создать и обновить указанную БД (несмотря на то, что мне сказали этого не делать).

Как и во многих существующих БД, которые нужно запрашивать, у меня есть разрешения SELECT, но нет разрешений на создание БД. Я не хочу, чтобы EF искажал создание ЛЮБЫХ объектов для этой конкретной БД (MyDb)

Есть пара странностей: 1. Модель не должна обновлять БД (соответствует представлению) 2. Database.SetInitializer(null) //Set on MVC Application_Start 3. Для устранения неполадок добавлено. doExist возвращает true, поэтому EF не должен пытаться создать БД. Вдвойне так с набором SetInitializer.

        using (var myDb = new MyDBContext1())
        {
            bool doesExist = myDb.Database.Exists(); //return true, the DB does exist!
        }

Надеюсь, я ошибаюсь, но это похоже на ошибку инициализатора в EF, которая не соответствует моим предпочтениям. Пожалуйста, докажите, что я ошибаюсь :)

О моей настройке: - Использование Visual Studio 2013 Preview и EF6 Beta 1 - В проекте есть еще одна модель «Code First» и DBContext2 (для другой БД). Эта БД у меня есть, и я могу создавать/обновлять БД в соответствии с изменениями модели (если захочу). В DBContext2 в течение некоторого времени для нее была включена миграция кода. Я удалил всю конфигурацию и таблицу миграции, думая, что это может косвенно повлиять на другой контекст (MyDBContext1), но это не помогло.

--Stack Trace-- //Почему здесь работают DBMigration и AutoMigrate??

//Конечно, разрешения запрещены. У меня нет доступа SA (и он мне не нужен) к этой конкретной БД, которая . Я просто хочу запустить операторы SELECT.

System.Data.SqlClient.SqlException was unhandled by user code
  HResult=-2146232060
  Message=CREATE TABLE permission denied in database 'MyDb'.
  Source=.Net SqlClient Data Provider
  ErrorCode=-2146232060
  Class=14
  LineNumber=1
  Number=262
  Procedure=""
  Server=MyDBServer
  State=1
  StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at System.Data.Entity.Infrastructure.InternalDispatcher`1.Dispatch[TResult](Func`1 operation, Action`1 executing, Func`3 executed)
       at System.Data.Entity.Infrastructure.DbCommandDispatcher.NonQuery(DbCommand command, DbInterceptionContext interceptionContext)
       at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
       at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
       at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
       at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
       at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass2f.<ExecuteStatements>b__2b()
       at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
       at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 func)
       at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action action)
       at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
       at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
       at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
       at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
       at System.Data.Entity.Migrations.Infrastructure.MigratorBase.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
       at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
       at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
       at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
       at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass9.<Update>b__8()
       at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
       at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
       at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
       at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update()
       at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
       at System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext)
       at System.Data.Entity.Database.Create(Boolean skipExistsCheck)
       at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
       at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassc`1.<CreateInitializationAction>b__b()
       at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
       at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
       at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
       at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
       at System.Data.Entity.Internal.InternalContext.Initialize()
       at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
       at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
       at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
       at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
       at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
.....
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
       at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3c()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass45.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3e()
  InnerException: 

person user756549    schedule 12.07.2013    source источник


Ответы (1)


У вас есть статический инициализатор в MyDBContext1?

static MyDBContext1()
{
    Database.SetInitializer<MyDBContext1>(null);
}
person qujck    schedule 12.07.2013