我已经彻底搜索了互联网,但找不到问题的明确答案。我有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.mdf
和User Instance=true
添加到我的连接字符串中,或者使用在machine.config中定义的LocalSqlServer
连接字符串,但在所有情况下都会覆盖现有的数据库。如果我删除Initial Catalog=aspnetdb
,那么我会收到一个错误,即需要初始目录。
答案 0 :(得分:4)
我遇到了同样的问题,但是this链接让我在赛道上找到了至少对我有用的东西。我希望至少这对某人有帮助! :)
我通常使用SQL Server Management Studio执行此操作。我用于此示例代码的数据库是SQL Server 2008R2,但我对您使用的SQL Server Express执行了相同的操作。
我使用以下工具,如果您在没有任何命令行参数的情况下使用它,就像向导一样工作。 %WINDIR%\ Microsoft.NET \框架\ v4.0.30319 \ aspnet_regsql.exe的
以下两行来自我制作的测试应用程序。请注意,第二个连接字符串(MyHealthContext)的名称与我用于代码优先类的DbContext的名称相同。
的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"/>
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;
使用步骤4中的sql替换下面的“SQL CODE GOES GOES”
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...
}
}
为了确保自定义数据库初始化程序不会在生产环境中意外运行,我添加了一个#if DEBUG语句,因为我总是在发布之前以发布模式编译我的代码。
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);
}
答案 1 :(得分:0)