我正在使用 UWP 学习 Entity Framework 。我尝试通过从 DbContext 中删除表来删除它。迁移后运行代码时,我收到一条错误,指出 UWP 不支持删除主键。 这篇文章,https://docs.efproject.net/en/latest/providers/sqlite/limitations.html ,建议使用sql(string)方法。 这篇文章,https://msdn.microsoft.com/en-us/data/jj592907.aspx ,有一个我正在尝试遵循的示例。
using (var context = new BloggingContext())
{
var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}
我找不到引用。 我喜欢使用 sql 语句的想法。 在另一篇 stackoverflow 文章中,How to drop a table in Entity Framework Code First? ,我不明白:“在 [DateStamp]_InitialCreate.cs 类的 Down 方法中写入 DropTable 语句,表将被删除”。与我的问题相关吗?如果是这样我该如何实现。 谢谢。
最佳答案
I tried dropping a table by deleting it from DbContext.
您可以使用db.Database.ExecuteSqlCommand
删除表:
//you have to use this namespace
using Microsoft.EntityFrameworkCore;
using (var db = new BloggingContext())
{
db.Database.ExecuteSqlCommand("DROP TABLE [Blogs]");
}
I don't understand: " write the DropTable statement in the Down method of [DateStamp]_InitialCreate.cs class
<DateStamp>_<MigrationName>.cs
是通过您的迁移生成的(Add-Migration MigrationName)。您可以在 Migrations 文件夹下找到它。在这个类文件中你可以找到 Down 方法。
每次您调用 db.Database.Migrate()
(通常在 App.xaml.cs
文件中)。 SQLite 将检查表 __EFMigrationsHistory
看看是否 <DateStamp>_<MigrationName>.cs
文件已被执行。您可以修改 [Migration("<TimeStamp>_<MigrationName>")]
的时间戳在以下文件中再次手动执行迁移:
并且您还可以根据自己的需求修改里面的代码进行迁移。
关于entity-framework - 在 Entity Framework Core 和 UWP 中删除表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38674100/