【发布时间】:2018-12-10 21:08:13
【问题描述】:
我正在尝试在我的基类上创建可重用的搜索查询,因此我不必为每个派生类重复相同的代码,但我无法让实体框架很好地发挥作用。
我有 3 个课程: CMEntityBase 网站 CMSiteServer
Site 和 SiteServer 均源自具有共同属性(ID、名称等)的 CMEntityBase
我想定义一些通用搜索: 例如获取姓名
using (var db = new LNOSCMDataModel())
{
db.Configuration.LazyLoadingEnabled = false;
var servers = db.CMSiteServers.
AsNoTracking().
GetByName(id,Active).
ConvertToAPIVM().ToList();
}
我尝试过几种方式来定义 GetByName:
基类:
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>();
}
泛型:
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>();
}
我尝试将基类定义为接口,并在泛型中使用 T : class, IEntity (interface) --> 这个方法来自:LINQ to Entities only supports casting EDM primitive or enumeration types with IEntity interface
最终他们都返回错误:
LINQ to Entities 仅支持使用 IEntity 接口转换 EDM 基元或枚举类型。
最后我想在基类属性上定义一个查询,但输出子类。现在看来我需要复制/粘贴每个派生类的方法。
【问题讨论】:
标签: c# entity-framework linq inheritance