使用NuGet获取EF6和SQLite的最新版本。在Stackoverflow上看了一些有用的帖子后,我终于让app.config文件起作用了。现在问题是虽然数据库已经创建了,但表格却没有被创建。
我的app.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<providers>
<provider invariantName="System.Data.SQLite"
type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite" />
<add name="SQLite Data Provider"
invariant="System.Data.SQLite"
description=".Net Framework Data Provider for SQLite"
type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider (Entity Framework 6)"
invariant="System.Data.SQLite.EF6"
description=".Net Framework Data Provider for SQLite (Entity Framework 6)"
type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="MyDBContext"
connectionString="Data Source=|DataDirectory|MyDB.sqlite"
providerName="System.Data.SQLite" />
</connectionStrings>
</configuration>
我的简单测试程序:
class Program
{
static void Main(string[] args)
{
using (var db = new MyDBContext())
{
db.Notes.Add(new Note { Text = "Hello, world" });
db.Notes.Add(new Note { Text = "A second note" });
db.Notes.Add(new Note { Text = "F Sharp" });
db.SaveChanges();
}
using (var db = new MyDBContext())
{
foreach (var note in db.Notes)
{
Console.WriteLine("Note {0} = {1}", note.NoteId, note.Text);
}
}
Console.Write("Press any key . . . ");
Console.ReadKey();
}
public class Note
{
public long NoteId { get; set; }
public string Text { get; set; }
}
public class MyDBContext : DbContext
{
// default constructor should do this automatically but fails in this case
public MyDBContext()
: base("MyDBContext")
{
}
public DbSet<Note> Notes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
如果我手动创建表格,程序就可以正常工作并更新表格。但是如果我删除了数据库,EF会重新创建数据库,但不会创建表格,当程序尝试读取数据时,会出现错误消息表格不存在。
有人成功地使用EF6实现了Code First吗?我现在完全陷入困境,希望能得到帮助/指导!!!
谢谢大家。