Home > Mobile >  Is there a better way to generalize dbSet with the same attribute - Entity Framework
Is there a better way to generalize dbSet with the same attribute - Entity Framework

Time:11-02

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.

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

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

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

CodePudding user response:

Creating a method that accepts a Func as a parameter is probably what you're looking for.


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

CodePudding user response:

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

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));
  • Related