entity-framework - 在 Entity Framework Core 和 UWP 中删除表

标签 entity-framework uwp code-first

我正在使用 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>")] 的时间戳在以下文件中再次手动执行迁移:

enter image description here

并且您还可以根据自己的需求修改里面的代码进行迁移。

关于entity-framework - 在 Entity Framework Core 和 UWP 中删除表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38674100/

相关文章:

c# - MVC 框架如何使用 DataAnnotations 验证代码优先 POCO?

entity-framework - 映射私有(private)属性时的问题

c# - 类型为“System.Data.SqlClient.SqlException”的未处理异常

audio - MediaPlayerElement vs MediaElement 选哪个?

windows - UWP 中未定义的边框显示

c# - 检测 Windows 10 系统电源状态

code-first - Entity Framework 5外键映射约定

sql-server - Entity Framework Multi-Tenancy 自定义共享表

c# - 使用 AutoMapper 6.1.1 创建 map

c# - 如何使用 linq to entities 获取字符串数组或 JSON 格式的数据?