简体   繁体   English

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

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

I have a common pattern我有一个共同的模式

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

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

[DBSet]=>Table in the database. [DBSet]=>数据库中的表。

If I create a method it is really easy to pass the exception message but the DB set seems to be the problem as the code doesn't know that there are PartId columns in different [DBset]s/tables如果我创建一个方法,它真的很容易传递异常消息,但数据库集似乎是问题,因为代码不知道不同 [DBset] s/表中有 PartId 列

What could be a way to bypass this problem and to create a common method?绕过这个问题并创建通用方法的方法是什么?

Edit: In 2 words, I want to pass the [DBSet] as a parameter编辑:在 2 个词中,我想将 [DBSet] 作为参数传递

This is the way that I would like this method to look like这是我希望这种方法看起来像的方式

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)
}

Creating a method that accepts a Func as a parameter is probably what you're looking for.创建一个接受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);
        }

Afterwards, you can consume it like this之后就可以这样消费了

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

I tried many different ways(with dynamic or DbSet< T>) but didn't think that I am filtering only on the ID so that's why I can just pass a List<int> and filter on it我尝试了许多不同的方法(使用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);
    }

And I call it like this我这样称呼它

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