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