【发布时间】:2020-02-15 00:26:54
【问题描述】:
尝试像以前使用存储库模式一样使用异步方法来发布实体,但是这次我想集成工作单元模式,这是我的界面:
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() 方法,我知道这没有任何意义,但直到现在我还没有找到如何针对这种特殊情况实现它。 当我尝试删除 await 时,出现以下错误:
无法将类型“void”隐式转换为“bool”
关于如何实施的任何建议?
【问题讨论】:
标签: c# entity-framework-core repository asp.net-core-webapi unit-of-work