如果数据库不存在,我想创建数据库。我使用sqlite
作为数据库源,并使用Entity Framework
。起初,我添加了新的模型(代码优先),并将当前目录中的数据库源设置为database.db
。如果不存在,创建数据库
接下来,我添加了简单的类:
class User {
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
当然数据库上下文和:
class TestContext : DbContext {
public DbSet<User> Users { get; set; }
public TestContext() :base("TestModel"){
//Create database always, even If exists
Database.SetInitializer<TestContext>(new DropCreateDatabaseAlways<TestContext>());
}
}
我已经在app.config
有connectionString
:
<connectionStrings>
<add name="TestModel" connectionString="data source="C:\Users\root\Documents\Visual Studio 2015\Projects\dbTEST\dbTEST\bin\Debug\database.db"" providerName="System.Data.SQLite.EF6" />
</connectionStrings>
而且出于某种原因运行这段代码后:
using (var ctx = new TextContext()) {
ctx.Database.Create();
}
我得到错误:
An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll
Additional information: Database 'main' cannot be created because it already exists.
我无法理解什么是错。我不知道数据库来自哪里main
。我将数据库文件设置为database.db
。你能帮助我吗?
===========解决方案如下:
您的构造函数规定每次启动应用程序时都会删除和创建数据库。
因此,删除ctx.Database.Create(),因为这是由框架处理。