0

I have a problem with rewriting part of my code to generic function which would be used in other methods.

this is example of code i want to rewrite:

if(!await _bikeDbContext.Order.AnyAsync(x => x.OrderId == orderId))
      {
        throw new BusinessNotFoundException("Order was not found");
      }

and this is something i'd like to have:

await _bikeDbContext.Order.IsAnyRule(x => x.OrderId == orderId));

I started writing code on my own but I have no clue what to put in function's body

public static void IsAnyRule<TEntity>(TEntity entity)
      where TEntity : class
    {
      
    }
4
  • 1
    If you want the usage as described, you'll need an extension method on DbSet<TEntity> Commented Sep 21, 2021 at 14:26
  • This should help: stackoverflow.com/questions/48860276/… Commented Sep 21, 2021 at 14:26
  • The methods you use are already generic. DbSet<T>.Find is already generic. .Any(...) is already generic. Why do you want something else? What actual problem are you trying to solve? Commented Sep 22, 2021 at 7:36
  • Why make an existence check instead of writing code that works whether the entity exists or not? Eg .FirstOrAsync will load the entity or return null if it's missing. Commented Sep 22, 2021 at 7:42

1 Answer 1

1
 public bool IsExist<TEntity>(Expression<Func<TEntity, bool>> predicate = null) where TEntity : class
        {
            IQueryable<TEntity> data = _bikeDbContext.Set<TEntity>();
            return data.Any(predicate);
        }

then use as

IsExist<Order>(x => x.OrderId == orderId);
Sign up to request clarification or add additional context in comments.

2 Comments

Probably better to use .Any(predicate) instead of .FirstOrDefault(predicate) != null, since FirstOrDefault will load the entity into the change tracker, which will change the behaviour of the code.
@huMptyduMpty this answerr is essentially just IQueryable<T>.Any(). It's not wrong. It's the question that makes little sense. IQueryable and DbSet methods are already generic

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.