c# - Entity Framework 代码优先 : how to add more props on model and update database?

标签 c# asp.net model entity-framework-core

我使用 Visual Studio 2017 创建了一个新的 ASP.NET Core 2.0 项目。目前我有一个 Coach 模型类:

public class Coach
{
        public int ID { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
        public string Methodology { get; set; }
        public string Price { get; set; }
        public int Rating { get; set; }

        //New property
        public string Email { get; set; }
}

我想向 Coach 类添加一个新属性 Email。我还想创建一个用于审查CoachReview 类。我的模型类 User 评论教练。但是,当我添加新属性和新类时,我会在 Web 应用程序启动时收到此消息:

A database operation failed while processing the request.

SqlException: Invalid column name 'Email'.

Applying existing migrations for ApplicationDbContext may resolve this issue. There are migrations for ApplicationDbContext that have not been applied to the database

00000000000000_CreateIdentitySchema
Apply Migrations

In Visual Studio, you can use the Package Manager Console to apply pending migrations to the database:

PM> Update-Database
Alternatively, you can apply pending migrations from a command prompt at your project directory:

dotnet ef database update

按照我收到的消息操作不起作用。问题仍然存在。谁能指出我正确的方向如何更新代码,然后更新本地存储的数据库?当首先更改模型代码并希望数据库反射(reflect)该更改时,工作流程应该是什么样的?

最佳答案

生成并运行迁移

Code First Migrations 有两个您需要运行的主要命令。

Add-Migration 将根据自上次迁移创建以来对模型所做的更改来构建下一次迁移

Update-Database 将把所有挂起的迁移应用到数据库 我们需要构建迁移来处理我们添加的新 Email 属性。 Add-Migration 命令允许我们为这些迁移命名,我们将其命名为 AddEmail

在程序包管理器控制台中运行Add-Migration AddEmail命令

在包管理器控制台中运行Update-Database命令

关于c# - Entity Framework 代码优先 : how to add more props on model and update database?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47617326/

相关文章:

c# - 无法获取局部或参数的值,因为它在此指令指针上不可用,可能是因为它已被优化掉

.net - 静态/共享功能中的LoadControl

c++ - 模型未使用 setContextProperty 更新

c# - 我如何为文本字段生成动态 ID 并从 asp.net 4 mvc3 中的模型数组获取数据

C#:如何访问窗体类外部的按钮

c# - 字节串在python和c#中是相同的,但是md5 hashcode是不同的

c# - 为什么 PresentViewControllerAsync 不阻塞?

c# - ASP.Net/C# : Replacing characters in a databound field

asp.net - 在现实世界的 ASP.NET 网站开发中,开发人员通常使用 VS 提供的登录控件集,还是开发自己的控件?

asp.net-mvc-3 - 包含路径表达式必须引用在类型上定义的导航属性