繁体   English   中英

有没有更好的方法来概括具有相同属性的 dbSet - Entity Framework

[英]Is there a better way to generalize dbSet with the same attribute - Entity Framework

我有一个共同的模式

bool doesLinkExist = await [DBSet]
.AnyAsync(model => model.PartId == parameters.PartId).ConfigureAwait(false);

if(doesLinkExist)
   throw exception (which has different messages)

[DBSet]=>数据库中的表。

如果我创建一个方法,它真的很容易传递异常消息,但数据库集似乎是问题,因为代码不知道不同 [DBset] s/表中有 PartId 列

绕过这个问题并创建通用方法的方法是什么?

编辑:在 2 个词中,我想将 [DBSet] 作为参数传递

这是我希望这种方法看起来像的方式

private Task CheckLinkExistAsync(int idForLookUp, string errorMsg, DBSet table, CancellationToken cancellationToken)
{
  bool LinkExist = await table.AnyAsync(model => model.Id == idForLookUp, cancellationToken).ConfigureAwait(false);

  if(LinkExist)
     throw exception (which has different messages)
}

创建一个接受Func作为参数的方法可能是您正在寻找的。


        private async Task<IActionResult> CheckLinkExistsAsync(int id, string errorMessage, Func<Task<T>> func)
        {
            bool exists = await _modelRepository.Any(x => x.Id == id);

            if (exists)
            {
                return await func();
            }
            throw new Exception(errorMessage);
        }

之后就可以这样消费了

await CheckLinkExistsAsync(1, "Custom Error Message", async () => {
  // DO STUFF AND RETURN
  var t = new T();
  return t;
});

我尝试了许多不同的方法(使用dynamic或 DbSet< T>),但并不认为我只对 ID 进行过滤,所以这就是为什么我可以只传递List<int>并对其进行过滤的原因

private void CheckLinkExistsAsync(int partId, string errorMessage, List<int> idsToLookup)
    {
        bool exists = idsToLookup.Any(id => id == partId);
        if(exists)
            throw new Exception(errorMessage);
    }

我这样称呼它

CheckLinkExistsAsync(parameters.PartId, "ExceptionMessage",
                await Db.Table.Select(model => model.PartId).ToListAsync(cancellationToken).ConfigureAwait(false));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM