I\'m quite new to C# and currently developing an application using the EntityFramework. I would like to extend the functionality of the database context class, so that I can cal
Unfortunately, in C#, you cannot overload a method by using a generic type constraint like this. You will have to give them different names like this
public class TestContext : DbContext
{
public DbSet ATests { get; set; }
public DbSet BTests { get; set; }
public IQueryable getPoolA() where T : TestA {
return (IQueryable)ATests;
}
public IQueryable getPoolB() where T : TestB {
return (IQueryable)BTests;
}
}
Another solution would be to do something like this:
public class TestContext : DbContext
{
public DbSet ATests { get; set; }
public DbSet BTests { get; set; }
public IQueryable getPool() {
return (typeof(T) == typeof(TestA))
? (IQueryable)ATests
: (IQueryable)BTests;
}
}
Now, you can make this even cleaner, since IQueryableT
, you can avoid casting:
public class TestContext : DbContext
{
public DbSet ATests { get; set; }
public DbSet BTests { get; set; }
public IQueryable getPool() {
return (typeof(T) == typeof(TestA)) ? ATests : BTests;
}
}
If you want to avoid testing for types you can do something like this:
public class TestContext : DbContext
{
readonly Dictionary _sets;
public DbSet ATests { get; set; }
public DbSet BTests { get; set; }
public TestContext()
{
_sets = new Dictionary
{
{ typeof(TestA), ATests },
{ typeof(TestB), BTests }
}
}
public IQueryable getPool() {
return (IQueryable)_sets[typeof(T)];
}
}