![](/img/trans.png)
[英]Proper Implementation of Unit of Work in Existing Repository Pattern in ASP.NET Core
[英]Asp.Net core Repository and Unit Of Work Pattern for Posting an entity
尝试使用像以前使用 Repository Pattern 那样的异步方法来发布实体,但这次我想集成 Unit Of Work 模式,这是我的界面:
public interface IUnitOfWork : IDisposable
{
. . .
void Save();
}
及其实现:
public class UnitOfWork : IUnitOfWork
{
private readonly DataContext _db;
public UnitOfWork(DataContext db)
{
_db = db;
. . .
}
. . .
public void Dispose()
{
_db.Dispose();
}
public void Save()
{
_db.SaveChanges();
}
}
这是我的方法:
[HttpPost]
public async Task<IActionResult> CreateItem(string userId, ItemForCreationDto itemForCreationDto)
{
if (userId != User.FindFirst(ClaimTypes.NameIdentifier).Value)
return Unauthorized();
itemForCreationDto.UserId = userId;
var item = _mapper.Map<Item>(itemForCreationDto);
if (item == null)
return BadRequest("Could not find item");
_uow.Item.Add(item);
if (await _uow.Save()) <--- Error here
{
var itemToReturn = _mapper.Map<ItemToReturnDto>(item);
return CreatedAtRoute("GetItem",
new { userId, id = item.Id }, itemToReturn);
}
throw new Exception("Creating the item failed on save");
}
但我得到以下错误:
等不及“空”了
那是因为我试图从异步 HttpPost 方法中调用一个无效的 Save() 方法,我知道这没有意义,但直到现在我找不到如何为这种特殊情况实现它。 当我尝试删除等待时,出现以下错误:
无法将类型“void”隐式转换为“bool”
关于如何实施的任何建议?
将接口重构为异步或添加其他成员
public interface IUnitOfWork : IDisposable {
//. . .
Task<bool> SaveAsync();
}
如果存在,它可能可以在实现中包装上下文的异步 API
public async Task<bool> SaveAsync() {
int count = await _db.SaveChangesAsync();
return count > 0;
}
允许所需的功能
//...
if (await _uow.SaveAsync()){
var itemToReturn = _mapper.Map<ItemToReturnDto>(item);
return CreatedAtRoute("GetItem", new { userId, id = item.Id }, itemToReturn);
}
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.