database - 将aspnetdb.mdf与我自己的数据库合并(自动生成)

标签 database asp.net-mvc connection-string aspnetdb

我已经彻底搜索了互联网,但找不到问题的明确答案。我有 aspnet.db 数据库。但是我想将自己的表和数据添加到该数据库中。如果我尝试使用连接字符串连接到它:

<add name ="ToernooiCompanionDBContext" connectionString ="Data Source= .\SQLEXPRESS; Integrated Security = SSPI; Trusted_Connection=True; Initial Catalog= aspnetdb"  providerName ="System.Data.SqlClient"/>

将在 C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA 中创建一个新数据库 (aspnetdb.mdf)。

我希望数据库(由 codefirst 自动生成)与我的 APP_DATA 文件夹中的现有数据库合并。我究竟做错了什么?

我已经尝试将 AttachDbFilename=|DataDirectory|aspnetdb.mdfUser Instance=true 添加到我的连接字符串,或者使用 LocalSqlServer 在 machine.config 中定义的连接字符串,但在所有情况下,这都会覆盖现有数据库。如果我删除 Initial Catalog=aspnetdb,则会收到需要初始目录的错误消息。

最佳答案

我有同样的问题但是this链接让我走上了至少对我有用的东西。我希望这至少对某人有帮助! :)

  1. 创建数据库
  2. 将 aspnet 表添加到新数据库
  3. 修复 web.config 中的数据库连接,使它们指向同一个数据库
  4. 编写一些删除除以“aspnet_”开头的表之外的所有表的 sql
  5. 将sql添加到自己写的数据库初始化器中
  6. 在 Global.asax.cs 中添加对数据库初始化程序的调用

1。创建数据库

我通常使用 SQL Server Management Studio 执行此操作。我在这个示例代码中使用的数据库是 SQL Server 2008R2,但我对您使用的 SQL Server Express 做了同样的操作。

2。将 aspnet 表添加到新数据库

我使用以下工具,如果您在没有任何命令行参数的情况下使用它,它就像一个向导。 %windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regsql.exe

3。修复数据库连接,使它们指向同一个数据库

以下两行来 self 做的测试应用。请注意,第二个连接字符串 (MyHealthContext) 的名称与我在代码第一类中使用的 DbContext 的名称相同。

数据库上下文:

public class MyHealthContext : DbContext
{
    public DbSet<Person> People { get; set; }
    public DbSet<PersonAttribute> PeopleAttributes { get; set; }
}

Web.config

<add name="ApplicationServices" connectionString="Server=localhost\mssql2008r2;Database=MyHealth;Integrated Security=True;" providerName="System.Data.SqlClient"/> 
<add name="MyHealthContext" connectionString="Server=localhost\mssql2008r2;Database=MyHealth;Integrated Security=True;" providerName="System.Data.SqlClient"/>

4。删除除 aspnetdb-tables 之外的所有内容的 SQL

DECLARE @cmdDropConstraints VARCHAR(4000)
DECLARE @cmdDropTables      VARCHAR(4000)

-- ======================================================================
-- DROP ALL THE FOREIGN KEY CONSTRAINTS FROM THE TABLES WE WANT TO DROP
-- ======================================================================
DECLARE cursorDropConstraints CURSOR FOR 
    SELECT 
        'ALTER TABLE ['+ s.name + '].[' + t.name + '] DROP CONSTRAINT [' + f.name +']' 
    FROM 
        sys.foreign_keys f 
        INNER JOIN sys.tables t ON f.parent_object_id=t.object_id 
        INNER JOIN sys.schemas s ON t.schema_id=s.schema_id 
    WHERE 
        t.is_ms_shipped=0
        AND t.name NOT LIKE 'aspnet_%'
        AND t.name <> 'sysdiagrams'

OPEN cursorDropConstraints
WHILE 1=1
BEGIN
    FETCH cursorDropConstraints INTO @cmdDropConstraints
    IF @@fetch_status != 0 BREAK
    EXEC(@cmdDropConstraints)
END
CLOSE cursorDropConstraints
DEALLOCATE cursorDropConstraints;

-- ======================================================================
-- DROP ALL THE RELEVANT TABLES SO THAT THEY CAN BE RECREATED
-- ======================================================================
DECLARE cursorDropTables CURSOR FOR 
    SELECT 
        'DROP TABLE [' + Table_Name + ']'
    FROM 
        INFORMATION_SCHEMA.TABLES
    WHERE
        Table_Name NOT LIKE 'aspnet_%'
        AND TABLE_TYPE <> 'VIEW'
        AND TABLE_NAME <> 'sysdiagrams'

OPEN cursorDropTables
WHILE 1=1
BEGIN
    FETCH cursorDropTables INTO @cmdDropTables
    IF @@fetch_status != 0 BREAK
    EXEC(@cmdDropTables)
END
CLOSE cursorDropTables
DEALLOCATE cursorDropTables;

5。数据库初始化代码:

将下面的“SQL CODE GOES HERE”替换为第 4 步中的 sql

public class MyHealthInitializerDropCreateTables : IDatabaseInitializer<MyHealthContext>
{
    public void InitializeDatabase(MyHealthContext context)
    {
        bool dbExists;
        using (new TransactionScope(TransactionScopeOption.Suppress))
        {
            dbExists = context.Database.Exists();
        }

        if (dbExists)
        {
            // Remove all tables which are specific to the MyHealthContext (not the aspnetdb tables)
            context.Database.ExecuteSqlCommand(@"SQL CODE GOES HERE");

            // Create all tables which are specific to the MyHealthContext (not the aspnetdb tables)
            var dbCreationScript = ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();
            context.Database.ExecuteSqlCommand(dbCreationScript);

            Seed(context);
            context.SaveChanges();
        }
        else
        {
            throw new ApplicationException("No database instance");
        }
    }

    protected virtual void Seed(MyHealthContext context)
    {
        //TODO: Add code for seeding your database with some initial data...
    }
}

6。 Hook 到新数据库初始化程序中的代码

为了确保自定义数据库初始化程序不会意外地在生产环境中运行,我添加了一个 #if DEBUG 语句,因为我总是在发布之前以 Release模式编译我的代码。

    protected void Application_Start()
    {
        //TODO: Comment out this database initializer(s) before going into production
        #if DEBUG
        Database.SetInitializer<MyHealthContext>(new MyHealthInitializerDropCreateTables()); // Create new tables in an existing database
        #endif

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

关于database - 将aspnetdb.mdf与我自己的数据库合并(自动生成),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10411937/

相关文章:

c# - 在 C# 中从 DataGridView 更新数据库表

python - 使用python在MySQL中多线程插入数据

c# - 在 MVC 脚本包中使用 CDN。我错过了什么?

c# - 在 Controller 上找不到公共(public)操作方法

c# - 未捕获 MySQL 异常 (C#)

c# - 我应该在哪里放置我的数据库连接字符串以及如何处理连接池?

mysql - 需要在mysql查询中获取超过50000条记录

mysql - 如何将两个 SQL 查询合并到一个查询中

c# - 从 lambda 表达式访问属性的 HtmlHelper 方法之间的区别

sql - 连接字符串不起作用,无法读取文件位置