使用实体框架创建 SQLite 数据库 [英] Create SQLite database using Entity Framework
问题描述
我正在尝试创建我的第一个数据库.我看到无数关于使用现有数据库和配置文件进行创建的帖子.不过,我想要实现的是从代码创建数据库,并在没有配置文件的情况下在代码内部进行初始化.
I am trying to create my first database. I see countless posts on creation being done using existing database and a config file. What I am trying to achieve though, is to create database from code and also do initialization inside code behind, without a config file.
我的 MyContext 类中有以下内容:
I have the following inside my MyContext class:
public MyContext() : base("MyDB")
{
DatabaseConfiguration _DBConfig = new DatabaseConfiguration();
}
public DbSet<MyObject> MyObject { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions
.Remove<PluralizingTableNameConvention>();
}
假设每当我创建 MyContext 的实例时,如果不存在,我应该创建一个数据库.但是没有创建文件.
Assuming that whenever I create an instance of MyContext, I should get a Database created if such does not exist. But no file gets created.
初始化如下:
class DatabaseConfiguration : DbConfiguration
{
public DatabaseConfiguration()
{
SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
SetProviderServices("System.Data.SQLite", (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));
}
}
我使用的是 NuGet 的最新版本的 SQLite 和 EF6.
I am using newest versions of SQLite and EF6 from NuGet.
推荐答案
您认为是在告诉它使用您的 DatabaseConfiguration
,但实际上并没有.简单地在构造函数中声明一个局部变量并不会告诉上下文使用该配置.您可以使用 DbConfigurationType
属性来判断.
You think you are telling it to use your DatabaseConfiguration
, but you're not. Simply declaring a local variable in your constructor doesn't tell the context to use that configuration. You can tell it with the DbConfigurationType
attribute.
[DbConfigurationType(typeof(DatabaseConfiguration))]
public class MyContext : DbContext
{
public MyContext() : base("MyDB")
{
}
public DbSet<MyObject> MyObject { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
这篇关于使用实体框架创建 SQLite 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!