-1

我正在从 VS 模板(从这里http://www.asp.net/single-page-application)查看 MVC4 的单页 Web 应用程序,看起来 ToDoLists 的 PUT 操作正在创建一个新的 ToDoList -为什么是这样?DTO 类定义中的代码:

public TodoList ToEntity()
        {
            TodoList todo = new TodoList
            {
                Title = Title,
                TodoListId = TodoListId,
                UserId = UserId,
                Todos = new List<TodoItem>()
            };
            foreach (TodoItemDto item in Todos)
            {
                todo.Todos.Add(item.ToEntity());
            }

            return todo;
        } 

从控制器:

public HttpResponseMessage PutTodoList(int id, TodoListDto todoListDto)
{           
    TodoList todoList = todoListDto.ToEntity();
    db.Entry(todoList).State = EntityState.Modified;
    db.SaveChanges();
    return Request.CreateResponse(HttpStatusCode.OK);
}

所以要更新记录,我们创建一个新记录?我对这是如何工作的有点困惑——任何澄清都会很棒。

4

1 回答 1

1

在此示例中,控制器将TodoListDto对象转换为TodoList对象,即数据库对象类型。由于 DTO 对象是从网页返回的,因此必须将其更改为适当的类型,以便 Entity Framework 可以将其附加到 DbSet 并保存更改。

ToEntity doesn't actually create a new record in the database, it creates a new TodoList instance which then gets attached, as modified to the database.

于 2013-03-01T03:03:34.457 回答