I am trying to create reusable search queries on my base class so i don't have to have the same code repeated for each dervived class but i cannot get entity framework to play nicely.
I have 3 classes: CMEntityBase CMSite CMSiteServer
Site & SiteServer are both derived from CMEntityBase which has common properties (ID, name, etc)
I want to define some generic searches: e.g. GetByName
using (var db = new LNOSCMDataModel())
{
db.Configuration.LazyLoadingEnabled = false;
var servers = db.CMSiteServers.
AsNoTracking().
GetByName(id,Active).
ConvertToAPIVM().ToList();
}
i have tried defining GetByName several ways:
base class:
public static IQueryable<CMEntityBase> GetByName(this IQueryable<CMEntityBase> Entities, string Name, bool Active = true)
{
return Entities.Where(ss => ss.Name == Name && ss.Active == Active || Active == false);//.Cast<IEntity>();
}
generics:
public static IQueryable<T> GetByName<T>(this IQueryable<CMEntityBase> Entities, string Name, bool Active = true) where T : CMEntityBase
{
return Entities.Where(ss => ss.Name == Name && ss.Active == Active || Active == false).Cast<T>();
}
i've tried defining the base class as an interface and in the generic using T : class, IEntity (interface) --> this approach came from: LINQ to Entities only supports casting EDM primitive or enumeration types with IEntity interface
ultimately they all return the error:
LINQ to Entities only supports casting EDM primitive or enumeration types with IEntity interface.
ultimately i want to define a query on the base class properties but output the child class. right now it appears i need to copy/paste my methods per derived class.