【问题标题】:Asp.Net core Repository and Unit Of Work Pattern for Posting an entity用于发布实体的 Asp.Net 核心存储库和工作单元模式
【发布时间】: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


    【解决方案1】:

    要么将接口重构为异步,要么添加一个额外的成员

    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);
    }
    
    //...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      相关资源
      最近更新 更多