【问题标题】:Should I detach entity from EF context when exposed it through Web API通过 Web API 公开实体时,我是否应该从 EF 上下文中分离实体
【发布时间】:2012-10-10 07:01:18
【问题描述】:

我正在使用 EF5 代码优先方法,我只是想知道在通过 Web API 公开实体时是否应该从 EF 上下文中分离实体?

假设我有 API 操作方法

[HttpGet]
public HttpResponseMessage Get(int id)
{
    var user = _userRepository.GetById(id);

    if (user != null)
    {
        // detach here???
        _userRepository.Detach(user);

        return Request.CreateResponse(HttpStatusCode.Found, user);
    }

    return Request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("No user with id={0} is found", id));
}

实际上,最好的做法是什么?我应该创建实体的投影然后将其暴露吗?

【问题讨论】:

  • 就个人而言,我不会将实体送回。我会为它创建一个基本类,并使用 AutoMapper(或类似的东西)将实体映射到 DTO 类。

标签: c# asp.net-mvc-3 entity-framework asp.net-mvc-4 asp.net-web-api


【解决方案1】:

我不认为 Detach 是必要的,当你取回它时它会自动分离。

但考虑到您只在请求/响应环境中使用它,那么首先使用 NoTracking 选项加载它是明智的。消除您永远不会使用的功能的开销。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    相关资源
    最近更新 更多