我一直在尝试使用单个DBContext以Code First的方式创建多个表格,但一直没有成功。我相信这只是因为我对框架不太熟悉,但我不确定我缺少什么。这里有一个简单的例子,包括实体和DBContext。
[Table("MyEntity")]
public class MyEntity
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string MyColumn { get; set; }
public int MyNumber { get; set; }
}
[Table("MySecondEntity")]
public class MySecondEntity
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string MyColumn { get; set; }
public int MyNumber { get; set; }
}
public class MyContext : DbContext
{
public DbSet<MyEntity> MyTable { get; set; }
public DbSet<MySecondEntity> MyTable2 { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionStringBuilder = new SqliteConnectionStringBuilder {DataSource = "test.db"};
var connectionString = connectionStringBuilder.ToString();
var connection = new SqliteConnection(connectionString);
optionsBuilder.UseSqlite(connection);
}
}
在我看来,它应该能正常工作。但是当我在下面的代码中调用它时,第一个foreach循环会抛出“没有这样的表:MyEntity”Sqlite异常。
static void Main(string[] args)
{
using (var db = new MyContext())
{
MyEntity testEntity1 = new MyEntity();
MySecondEntity entity1 = new MySecondEntity();
testEntity1.MyColumn = "Test Data 1";
testEntity1.MyNumber = 12345;
db.MyTable.Add(testEntity1);
db.Database.Migrate();
entity1.MyColumn = "New Data 1";
entity1.MyNumber = 2;
db.MyTable2.Add(entity1);
db.Database.Migrate();
Console.WriteLine("Inserting Data...");
Console.WriteLine("Data in the Database");
foreach (var entity in db.MyTable)
{
Console.WriteLine("Id: " + entity.Id);
Console.WriteLine("Column Data: " + entity.MyColumn);
Console.WriteLine("Number: " + entity.MyNumber);
}
foreach (var entity in db.MyTable2)
{
Console.WriteLine("Id: " + entity.Id);
Console.WriteLine("Column Data: " + entity.MyColumn);
Console.WriteLine("Number: " + entity.MyNumber);
}
}
Console.WriteLine("Examples run finished,press Enter to continue...");
Console.ReadLine();
}
我几乎可以保证我遗漏了一些简单的东西,但我似乎找不到它,并且在他们的文档中找不到任何示例。这里在 GitHub 上提交了一个类似的问题https://github.com/aspnet/EntityFramework/issues/2874,但那是针对多个上下文的。所以也许这是另一件尚未完全发布的东西? 解决方案 按照 @natemcmaster 推荐的 http://ef.readthedocs.org/en/latest/getting-started/uwp.html 上发布的教程和 @lukas-kabrt 建议的解决方案,我成功地将其工作。通过运行下面的命令,我能够创建表并从其中插入/选择数据。
Install-Package EntityFramework.Commands –Pre
Add-Migration MyFirstMigration
Update-Database