【发布时间】:2019-08-14 02:24:45
【问题描述】:
当我不打算写任何东西时,我通常使用 AsNoTracking。我应该如何在 dbContext 隐藏在它后面的服务层中处理这个问题? (我将 EF 核心视为存储库,因为它是存储库)
public class SomeService
{
//...
public SomeEntity GetById(int id)
{
return _dbContext.Find(id);
}
public SomeEntity GetReadonlyById(int id)
{
return _dbContext.SomeEntitities.AsNoTracking().SingleOrDefault(e => e.Id == id);
}
public SomeEntity Update(SomeEntity someEntity)
{
_dbContext.Update(someEntity);
_dbContext.SaveChanges();
}
}
public class SomeController
{
private readonly SomeService _someService;
//....
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var someEntity = _someService.GetReadonlyById(id);
if (someEntity == null)
{
return NotFound();
}
return someEntity;
}
[HttpPut("{id}")]
public IActionResult Modify(int id, SomeEntity modified)
{
var someEntity = _someService.GetById(id);
if (someEntity == null)
{
return NotFound();
}
someEntity.Someproperty = modified.Someproperty;
_someService.Update(someEntity);
return Ok(someEntity);
}
}
有没有更好的方法来做到这一点?
我还可以如下定义我的服务:
public class SomeService
{
//...
public SomeEntity GetById(int id)
{
return _dbContext.AsNoTracking.SingleOrDefault(e => e.Id == id);
}
public SomeEntity Update(int id, SomeEntity someEntity)
{
var entity = _dbContext.SomeEntities.Find(id);
if (entity == null)
{
return null;
}
entity.Someproperty = someEntity.Someproperty;
_dbContext.Update(entity);
_dbContext.SaveChanges();
return entity;
}
}
public class SomeController
{
private readonly SomeService _someService;
//....
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var someEntity = _someService.GetById(id);
if (someEntity == null)
{
return NotFound();
}
return someEntity;
}
[HttpPut("{id}")]
public IActionResult Modify(int id, SomeEntity modified)
{
var someEntity = _someService.Update(id, modified);
if (someEntity == null)
{
return NotFound();
}
return Ok(someEntity);
}
}
有什么更好的方法?
【问题讨论】:
-
我更喜欢第二种方法。如果我们不得不谈论关注分离设计,那么 Repository 应该只知道如何从上下文而不是外部层获取和更新数据。
-
@user1672994 我认为你是对的。我不需要关心如何从我的控制器更新它,因为服务会为我完成它并且实现细节是隐藏的。
-
这让我很困惑,因为每个人的做法都不一样,而且大多数情况下实现中没有 AsNoTracking,或者只是没有人关心这个功能。
-
即使在这里github.com/dotnet-architecture/eShopOnContainers 也没有使用它,也没有关于如何处理这个问题的任何官方建议
-
不知何故您的 SomeService 是一个存储库。有所有的并发症和缺点。
标签: c# asp.net-core domain-driven-design entity-framework-core asp.net-core-webapi