I am using EF5 code-first approach and I am just wondering should I detach entity from EF context when exposed it through the Web API?
Let’s say I have API action method
[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));
}
Actually what are the best practices for that? Should I create the projection of the entity and then exposed it?
I don’t believe Detach is necessary, it will automatically be detached when you ever get it back.
But considering that you only use it in a Request/Response environment, then it is sensible to load it with the NoTracking option in the first place. Eliminate overhead for functionality you will never use.