Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework 为什么要使用实体框架';DBS实体?_Entity Framework_Asp.net Mvc 4 - Fatal编程技术网

Entity framework 为什么要使用实体框架';DBS实体?

Entity framework 为什么要使用实体框架';DBS实体?,entity-framework,asp.net-mvc-4,Entity Framework,Asp.net Mvc 4,当我基于VS2012单页MVC Web应用程序生成一个项目时,基础项目包含大量对DbEntity的引用 原因: 而不仅仅是: todoList.UserId 它在示例ApicController中重复使用此间接寻址,但只调用一次DbEntityEntry特定的成员(状态属性)。是否有一些我忽略的重要原因 编辑:这里有一个更大的片段 // DELETE api/TodoList/5 [ValidateHttpAntiForgeryToken] public HttpResponseMessage

当我基于VS2012单页MVC Web应用程序生成一个项目时,基础项目包含大量对DbEntity的引用

原因:

而不仅仅是:

todoList.UserId
它在示例ApicController中重复使用此间接寻址,但只调用一次DbEntityEntry特定的成员(状态属性)。是否有一些我忽略的重要原因

编辑:这里有一个更大的片段

// DELETE api/TodoList/5
[ValidateHttpAntiForgeryToken]
public HttpResponseMessage DeleteTodoList(int id) {
    TodoList todoList = db.TodoLists.Find(id);
    if (todoList == null) {
        return Request.CreateResponse(HttpStatusCode.NotFound);
    }

    if (db.Entry(todoList).Entity.UserId != User.Identity.Name) {
        // Trying to delete a record that does not belong to the user
        return Request.CreateResponse(HttpStatusCode.Unauthorized);
    }

我相信它可以让您确保引用的是数据库实体,而不仅仅是数据库中可能不存在的(该模型类的)实例。

通过
db.TodoLists.Find()检索对象时,这似乎毫无意义。那么,这只是一些程序员在构建示例时练习语义预防吗?在我看来,由于示例中的db上下文位于实例上,因此即使Find(id)也无法从内存中返回任何内容。是的,Find()可以返回未持久化的实体,但即使它可以(假设我从示例中修改了DbContext的范围),我也希望将其删除,在这个代码示例中,@millimoose脚手架机制已经生成了正确的代码,因此,自然地,
Find()
返回的模型实例将是
DbSet
中的一个,无论如何,是的。但是,用户可以修改代码(不要忘记,生成的操作只是一个起点,并鼓励根据应用程序的需要进行更改)。因此,证明这种可能性并非毫无意义。谢谢你们。这场讨论为我提供了一个立足点,说明我为什么会/不会需要它。看起来像是新手式的冗余,或者是一种对分离实体有偏执狂的人会普遍采用的模式。谢谢millimoose。是的,一个独立的实体更有意义。在这个示例中不可能发生这种情况,但我可以看出,如果我忙于执行实现原始实体而不是DTO或ViewModels的控制器操作,那么这种情况比未持久化的实体更可能发生在我身上。:)(读作:“如果我是一个懒汉,我可以看出这将是一个问题”)
// DELETE api/TodoList/5
[ValidateHttpAntiForgeryToken]
public HttpResponseMessage DeleteTodoList(int id) {
    TodoList todoList = db.TodoLists.Find(id);
    if (todoList == null) {
        return Request.CreateResponse(HttpStatusCode.NotFound);
    }

    if (db.Entry(todoList).Entity.UserId != User.Identity.Name) {
        // Trying to delete a record that does not belong to the user
        return Request.CreateResponse(HttpStatusCode.Unauthorized);
    }