【问题标题】:Code first and changing model class, how to update model without recreate the table?代码优先和更改模型类,如何在不重新创建表的情况下更新模型?
【发布时间】:2013-02-01 03:45:21
【问题描述】:

我使用新的 Asp.Net MVC 4 单页应用程序创建了一个项目。我运行了 Web 应用程序并创建了默认的 Sql Server localDB 数据库,以及以下类的表。

public class TodoItem
{
    public int TodoItemId { get; set; }

    [Required]
    public string Title { get; set; }
    public bool IsDone { get; set; }
    // public string Test { get; set; }

    [ForeignKey("TodoList")]
    public int TodoListId { get; set; }
    public virtual TodoList TodoList { get; set; }
}

}

然后

  1. 我发现我需要为Title 列生成varchar(max) 的数据库。我将其修改为varchar(500)。 (alter table todoitems alter column Title varchar(500) not null) Web 应用程序可以毫无问题地运行。
  2. 然后我在类中添加一个新属性(取消注释 Test 属性)。运行网络应用时出现以下异常。

支持“TodoItemContext”上下文的模型在创建数据库后发生了变化。考虑使用 Code First 迁移来更新数据库 (http://go.microsoft.com/fwlink/?LinkId=238269)。

[Authorize]
public class TodoListController : ApiController
{
    private TodoItemContext db = new TodoItemContext();

    // GET api/TodoList
    public IEnumerable<TodoListDto> GetTodoLists()
    {
        return db.TodoLists.Include("Todos")
            .Where(u => u.UserId == User.Identity.Name)
            .OrderByDescending(u => u.TodoListId)
            .AsEnumerable()
            .Select(todoList => new TodoListDto(todoList));
    }
  1. 我尝试修改数据库表(alter table todoitems add Test varchar(200)),但仍然引发异常。

是否可以更改模型类并修改(通过 VisualStudio 或手动)表而不是重新创建表? (我想在数据库表上保留我的手动更改。)

【问题讨论】:

    标签: c# asp.net-mvc-4 ef-code-first


    【解决方案1】:

    您要查找的内容称为 Code First Migrations - 您可以在 MSDN 上查看精彩的演练:http://msdn.microsoft.com/en-us/data/jj591621.aspx

    【讨论】:

      猜你喜欢
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多