MVC 3,MVCScaffolding。使用SQLCe而不是Express。没有创建数据库文件

时间:2011-05-12 13:13:25

标签: asp.net asp.net-mvc-3 sql-server-ce-4

我一直在使用新的MVCScaffolding作为我的下一个CMS,到目前为止它已经很棒了。很棒,直到我想将我的SQLExpress默认数据库更改为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
    }
}

1 个答案:

答案 0 :(得分:0)

汤姆,

我也遇到过Sql CE和Entity Framework的问题。但是,我或许能够解释你所引用的帖子,因为我已经精通使用它,因为我已经通过它进行了战斗。

首先,该博客文章是针对MVCScaffolding NuGet包的。不知道你是否知道这个套装的功能,但它基本上增加了对Scott&amp; Sons的脚手架的参考。创建公司以在构建模型后为您动态生成CRUD。

我的理解是,一旦你创建了一个模型,构建你的项目,你就可以在Package Manager Console中运行以下命令,它将创建我上面提到的CRUD。

Scaffold Controller [WhateverYourModelNameIs]

现在,一旦完成此过程,它将在Models文件夹下为您的应用程序生成一个Context类。如果你在Start方法的代码中看到了上面的代码(对于SQLCEEntityFramework.cs),它会提到你需要取消注释方法的最后一行,以便它创建db(如果它不存在)。

最后,一旦执行了应用程序,就应该“创建”SQL CE数据库,如果单击App_Data文件夹并选择解决方案资源管理器顶部的“显示所有文件”并点击“刷新”图标,应该看到你的数据库。

<强>更新

很抱歉,经过测试,汤姆,你是对的。创建数据库的唯一方法是执行Scaffolder创建的其中一个视图。