C
C#4w ago
biohazrd

Generics w/ EF Core

I have an API that I don't control that looks something like this:
public interface ICategorized { public int CategoryId { get; set; } }
public interface ITypeA { }
public interface ITypeB { }
public class CategoryA : ICategorized, ITypeA { public int CategoryId { get; set; } }
public class StreamA : ICategorized, ITypeA { public int CategoryId { get; set; } }
public class CategoryB : ICategorized, ITypeB { public int CategoryId { get; set; } }
public class StreamB : ICategorized, ITypeB { public int CategoryId { get; set; } }
public interface ICategorized { public int CategoryId { get; set; } }
public interface ITypeA { }
public interface ITypeB { }
public class CategoryA : ICategorized, ITypeA { public int CategoryId { get; set; } }
public class StreamA : ICategorized, ITypeA { public int CategoryId { get; set; } }
public class CategoryB : ICategorized, ITypeB { public int CategoryId { get; set; } }
public class StreamB : ICategorized, ITypeB { public int CategoryId { get; set; } }
I want to be able to create and store Filter objects in my database:
public class FilterA { public int CategoryId { get; set; } }
public class FilterB { public int CategoryId { get; set; } }
public DbSet<FilterA> AFilters { get; set; }
public DbSet<FilterB> BFilters { get; set; }
public class FilterA { public int CategoryId { get; set; } }
public class FilterB { public int CategoryId { get; set; } }
public DbSet<FilterA> AFilters { get; set; }
public DbSet<FilterB> BFilters { get; set; }
However, when trying to use generic methods, I can't access the DbSet for the particular filter that I need:
public IEnumerable<T> Filter<T>(this IEnumerable<T> items) where T : ICategorized
{
// Doesnt work because I don't have DbSets of CategoryA/StreamA or B
var filters = context.Set<T>().ToList();

// Doesnt work because cant do pattern matching on generic type parameters and also ick
if (T is A)
{
var filters = context.Set<FilterA>().ToList();
}
}
public IEnumerable<T> Filter<T>(this IEnumerable<T> items) where T : ICategorized
{
// Doesnt work because I don't have DbSets of CategoryA/StreamA or B
var filters = context.Set<T>().ToList();

// Doesnt work because cant do pattern matching on generic type parameters and also ick
if (T is A)
{
var filters = context.Set<FilterA>().ToList();
}
}
Basically, I want to easily be able to retrieve (or add) the appropriate Filter from my database, while keeping my various methods generic
2 Replies
ero
ero4w ago
are you looking for if (typeof(T) == typeof(A))?
Sehra
Sehra4w ago
Inheritance - EF Core
How to configure entity type inheritance using Entity Framework Core

Did you find this page helpful?