I created a project using the newly Single page application of Asp.Net MVC 4. I ran the web app and the default Sql Server localDB database is created, as well as the Tables for the following class.
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; }
}
}
Then
- I found that I need the database generated
varchar(max)for columnTitle. I modified it tovarchar(500). (alter table todoitems alter column Title varchar(500) not null) The web app can be run without any problem. - Then I add a new property in the class (uncomment the Test property). I got the following exception when running the web app.
The model backing the ‘TodoItemContext’ context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
on
[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));
}
- I tried to modify the database table (
alter table todoitems add Test varchar(200)), but the exception is still raised.
Is it possible to change the model class and modify (either by VisualStudio or manully) the table instead of recreate it? (I want to keep my manually changes on the database tables.)
What you’re looking for is called
Code First Migrations– you can see a great walk-through on MSDN: http://msdn.microsoft.com/en-us/data/jj591621.aspx