实体框架和转换<>
本文关键字:转换 框架 实体 | 更新日期: 2023-09-27 18:32:25
我有这个类(你可以在这里看到它的完整)...
internal class BaseRepository<I, C> : IRepository<I>
where I : class, IBaseObject
where C : BaseObject
{
private Context _context;
public IEnumerable<I> FindBy(Expression<Func<I, bool>> predicate)
{
return _context.Set<C>().ToList().Cast<I>().AsQueryable().Where(predicate);
}
// other methods.
}
我该怎么做,这样我就不必调用.ToList()
,我相信这会导致 EF 返回所有内容.Set<C>()
在不.ToList()
和.AsQueryable()
的情况下使用它会导致错误:
System.NotSupportedException:无法将类型"Sln.DAL.Sql.Entities.Project"转换为类型"Sln.DAL.Entities.IProject"。LINQ to 实体仅支持强制转换 EDM 基元或枚举类型。
如果我们添加一个约束
internal class BaseRepository<I, C> : IRepository<I>
where I : class, IBaseObject
where C : BaseObject, I
那么我们可以使用
_context.Set<C>().Where(predicate).AsEnumerable();