0

I am trying to specify the table I would like _context to work with based on the request parameters.

I have 2 tables e.g. Chair, Table in my _context all of which implement interface IProduct.

I would like to create a function, that would return either DbSet<Chair> or DbSet<Table>

After 2 hours of searching I cannot understand how to do it.

One of my attempts was:

public DbSet<IProduct> GetDbSet(bool condition)
{
  if (condition)
     {
          return _context.Set<Chair>();
     }
 else
     {
         return _context.Set<Table>();
     }
}

It generates "Cannot implicitly convert Chair to IProduct etc.

I am new to C# and I believe there must be a simple way to do this, but almost giving up on finding it.

[Possible Solution]

[Update] Following Ivan's comment, changed the type of extension to IQueryable.

Thanks to the comments I came up with the idea to move the query methods into the DbSet extension and then call it for each of the DbSet depending on the conditions.

This looks like (my example above is artificial, so I'd omit the actual query):

public static class IQueryableExtensions
{
  public static decimal getTotalSales<T>(this IQueryable<T>) where T: class, IProduct
  {
     var result = dbSet
                  .Where(...)
                  .Sum(x => (decimal)x.Sales);   
      
  }
}

Then I can use:

if (condition)
{ 
     return _context.Chair.getTotalSales()
}
else{ 
     return _context.Book.getTotalSales()
}
Alex S.
  • 974
  • 1
  • 13
  • 18
  • 1
    I think this is problematic. You could define `IProduct` and them implement it in both your `DBSets`. But I suspect the change tracking and internal logic is not going to work in a generic way. What do you need to do with the `DBSet`? Will you make changes? What does `IProduct` look like? – Jonathan Wood Mar 05 '23 at 05:06
  • 1
    Sounds like you might want to consider the Factory design pattern to resolve which DbSet you want at runtime. Check [this answer](https://stackoverflow.com/a/57790127/281278) and see if it helps. – Peppermintology Mar 05 '23 at 05:48
  • Yes, I ended up moving my queries into DbSet extension methods and subsequently calling the methods on different DbSet for different conditions. – Alex S. Mar 05 '23 at 06:07
  • 1
    @AlexS. Brilliant. Perhaps post your solution as an answer for others? Might be beneficial to others in the future. – Peppermintology Mar 05 '23 at 06:15
  • 1
    Generally speaking, you should base your custom query methods on `IQueryable` (like LINQ and EF Core do) rather than specific class implementations like `DbSet`. – Ivan Stoev Mar 05 '23 at 07:55

0 Answers0