2011-05-12 1 views
0

저는 다음 CMS에 새로운 MVCScaffolding을 사용하고 있으며 지금까지 끝내주었습니다. 내 SQLExpress 기본 데이터베이스를 SQLCe 로컬 데이터베이스로 변경할 때까지 훌륭합니다.MVC 3, MVCScaffolding. Express 대신 SQLCe 사용. 데이터베이스 파일이 생성되지 않았습니다

여기에 (http://blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/) 내가 "EFCodeFirst.SqlServerCompact"패키지를 설치하면 변경하고 데이터베이스 파일을 만드는 일을 처리한다고합니다. 그래서 나는 그것을했다.

"SQLCEEntityFramework.cs"이라는 파일을 만들었습니다.이 파일에는 오류가있었습니다. "System.Data.Entity.Database"에 대한 참조는 더 이상 존재하지 않으며 DbDatabase에 대한 참조는 현재 Database입니다. 그래서 그 오류를 수정하고 응용 프로그램을 실행했습니다.

모든 것이 정상적으로 실행되지만 연결 문자열이 내 Web.config에 추가되지 않으며 데이터베이스 파일이 내 App_Data 디렉토리에 생성되지 않습니다. 그래서 지금 내가 뭔가 잘못하고 있는지 궁금해지기 시작했습니다 ...

아무도 여기에서 무슨 일이 일어나고 있는지 그리고 어떻게 고치려하는지 전혀 알지 못합니까?

고맙습니다.

편집 : 그냥 경우에 당신은 SQLCEEntityFramework.cs 파일에 무엇을보고 싶어 :

using System; 
using System.Data.Entity; 
using System.Data.SqlServerCe; 
using System.IO; 
using System.Transactions; 
using System.Data.Entity.Infrastructure; 

[assembly: WebActivator.PreApplicationStartMethod(typeof(CMS.App_Start.SQLCEEntityFramework), "Start")] 

namespace CMS.App_Start { 
    public static class SQLCEEntityFramework { 
     public static void Start() { 
      Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0"); 

      // Sets the default database initialization code for working with Sql Server Compact databases 
      // Uncomment this line and replace CONTEXT_NAME with the name of your DbContext if you are 
      // using your DbContext to create and manage your database 
      //DbDatabase.SetInitializer(new CreateCeDatabaseIfNotExists<CONTEXT_NAME>()); 
     } 
    } 

    public abstract class SqlCeInitializer<T> : IDatabaseInitializer<T> where T : DbContext { 
     public abstract void InitializeDatabase(T context); 

     #region Helpers 

     /// <summary> 
     /// Returns a new DbContext with the same SqlCe connection string, but with the |DataDirectory| expanded 
     /// </summary> 
     /// <param name="context"></param> 
     /// <returns></returns> 
     protected static DbContext ReplaceSqlCeConnection(DbContext context) { 
      if (context.Database.Connection is SqlCeConnection) { 
       SqlCeConnectionStringBuilder builder = new SqlCeConnectionStringBuilder(context.Database.Connection.ConnectionString); 
       if (!String.IsNullOrWhiteSpace(builder.DataSource)) { 
        builder.DataSource = ReplaceDataDirectory(builder.DataSource); 
        return new DbContext(builder.ConnectionString); 
       } 
      } 
      return context; 
     } 

     private static string ReplaceDataDirectory(string inputString) { 
      string str = inputString.Trim(); 
      if (string.IsNullOrEmpty(inputString) || !inputString.StartsWith("|DataDirectory|", StringComparison.InvariantCultureIgnoreCase)) { 
       return str; 
      } 
      string data = AppDomain.CurrentDomain.GetData("DataDirectory") as string; 
      if (string.IsNullOrEmpty(data)) { 
       data = AppDomain.CurrentDomain.BaseDirectory ?? Environment.CurrentDirectory; 
      } 
      if (string.IsNullOrEmpty(data)) { 
       data = string.Empty; 
      } 
      int length = "|DataDirectory|".Length; 
      if ((inputString.Length > "|DataDirectory|".Length) && ('\\' == inputString["|DataDirectory|".Length])) { 
       length++; 
      } 
      return Path.Combine(data, inputString.Substring(length)); 
     } 

     #endregion 
    } 

    /// <summary> 
    /// An implementation of IDatabaseInitializer that will recreate and optionally re-seed the 
    /// database only if the database does not exist. 
    /// To seed the database, create a derived class and override the Seed method. 
    /// </summary> 
    /// <typeparam name="TContext">The type of the context.</typeparam> 
    public class CreateCeDatabaseIfNotExists<TContext> : SqlCeInitializer<TContext> where TContext : DbContext { 
     #region Strategy implementation 

     public override void InitializeDatabase(TContext context) { 
      if (context == null) { 
       throw new ArgumentNullException("context"); 
      } 
      var replacedContext = ReplaceSqlCeConnection(context); 

      bool databaseExists; 
      using (new TransactionScope(TransactionScopeOption.Suppress)) { 
       databaseExists = replacedContext.Database.Exists(); 
      } 

      if (databaseExists) { 
       // If there is no metadata either in the model or in the databaase, then 
       // we assume that the database matches the model because the common cases for 
       // these scenarios are database/model first and/or an existing database. 
       if (!context.Database.CompatibleWithModel(throwIfNoMetadata: false)) { 
        throw new InvalidOperationException(string.Format("The model backing the '{0}' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.", context.GetType().Name)); 
       } 
      } 
      else { 
       context.Database.Create(); 
       Seed(context); 
       context.SaveChanges(); 
      } 
     } 

     #endregion 

     #region Seeding methods 

     /// <summary> 
     /// A that should be overridden to actually add data to the context for seeding. 
     /// The default implementation does nothing. 
     /// </summary> 
     /// <param name="context">The context to seed.</param> 
     protected virtual void Seed(TContext context) { 
     } 

     #endregion 
    } 

    /// <summary> 
    /// An implementation of IDatabaseInitializer that will <b>DELETE</b>, recreate, and optionally re-seed the 
    /// database only if the model has changed since the database was created. This is achieved by writing a 
    /// hash of the store model to the database when it is created and then comparing that hash with one 
    /// generated from the current model. 
    /// To seed the database, create a derived class and override the Seed method. 
    /// </summary> 
    public class DropCreateCeDatabaseIfModelChanges<TContext> : SqlCeInitializer<TContext> where TContext : DbContext { 
     #region Strategy implementation 

     /// <summary> 
     /// Executes the strategy to initialize the database for the given context. 
     /// </summary> 
     /// <param name="context">The context.</param> 
     public override void InitializeDatabase(TContext context) { 
      if (context == null) { 
       throw new ArgumentNullException("context"); 
      } 

      var replacedContext = ReplaceSqlCeConnection(context); 

      bool databaseExists; 
      using (new TransactionScope(TransactionScopeOption.Suppress)) { 
       databaseExists = replacedContext.Database.Exists(); 
      } 

      if (databaseExists) { 
       if (context.Database.CompatibleWithModel(throwIfNoMetadata: true)) { 
        return; 
       } 

       replacedContext.Database.Delete(); 
      } 

      // Database didn't exist or we deleted it, so we now create it again. 
      context.Database.Create(); 

      Seed(context); 
      context.SaveChanges(); 
     } 

     #endregion 

     #region Seeding methods 

     /// <summary> 
     /// A that should be overridden to actually add data to the context for seeding. 
     /// The default implementation does nothing. 
     /// </summary> 
     /// <param name="context">The context to seed.</param> 
     protected virtual void Seed(TContext context) { 
     } 

     #endregion 
    } 

    /// <summary> 
    /// An implementation of IDatabaseInitializer that will always recreate and optionally re-seed the 
    /// database the first time that a context is used in the app domain. 
    /// To seed the database, create a derived class and override the Seed method. 
    /// </summary> 
    /// <typeparam name="TContext">The type of the context.</typeparam> 
    public class DropCreateCeDatabaseAlways<TContext> : SqlCeInitializer<TContext> where TContext : DbContext { 
     #region Strategy implementation 

     /// <summary> 
     /// Executes the strategy to initialize the database for the given context. 
     /// </summary> 
     /// <param name="context">The context.</param> 
     public override void InitializeDatabase(TContext context) { 
      if (context == null) { 
       throw new ArgumentNullException("context"); 
      } 
      var replacedContext = ReplaceSqlCeConnection(context); 

      if (replacedContext.Database.Exists()) { 
       replacedContext.Database.Delete(); 
      } 
      context.Database.Create(); 
      Seed(context); 
      context.SaveChanges(); 
     } 

     #endregion 

     #region Seeding methods 

     /// <summary> 
     /// A that should be overridden to actually add data to the context for seeding. 
     /// The default implementation does nothing. 
     /// </summary> 
     /// <param name="context">The context to seed.</param> 
     protected virtual void Seed(TContext context) { 
     } 

     #endregion 
    } 
} 

답변

0

톰 나도는 SQL CE와 엔티티 프레임 워크 문제가 발생 된

합니다. 하지만 내가 참조 할만한 게시물을 설명 할 수 있을지도 모르니, 지금 내가 그것을 통해 자신의 길을 걸어 다녔다.

처음에는 블로그 항목이 MVCScaffolding NuGet 패키지 용이었습니다. 이 패키지가 무엇인지 알지는 모르지만 기본적으로 모델을 작성한 후에 Scott & 회사가 생성 한 Scaffolder에 대한 참조가 동적으로 생성됩니다.

일단 모델을 만들고 프로젝트를 빌드하면 패키지 관리자 콘솔에서 다음 명령을 실행하면 위에서 언급 한 CRUD가 생성됩니다.

Scaffold Controller [WhateverYourModelNameIs] 

이제이 프로세스가 완료되면 Models 폴더 아래에서 응용 프로그램에 대한 Context 클래스가 생성됩니다. Start 메서드의 코드 (SQLCEEntityFramework.cs)에서 위의 내용을 보면 메서드가없는 경우 db를 만들 수 있도록 메서드의 마지막 줄의 주석 처리를 제거해야한다는 내용이 나와 있습니다.

마지막으로 응용 프로그램을 실행하고 나면 SQL CE 데이터베이스를 만들어야하며 App_Data 폴더를 클릭하고 솔루션 탐색기 상단의 '모든 파일 표시'를 선택하고 새로 고침 아이콘을 누르면, 당신은 당신의 데이터베이스를보아야한다.

UPDATE :

그래서 죄송합니다,이 테스트를 한 후, 톰, 당신이 올바른지. Scaffolder가 생성 한 뷰 중 하나를 실행하면 데이터베이스가 생성됩니다.

관련 문제