【发布时间】:2016-09-23 05:56:23
【问题描述】:
我正在尝试使一些代码更具可读性,但并没有完全掌握如何构建扩展方法和/或表达式来做到这一点。我们目前有许多实体上都有RecordStatusTypeId(从IRecordStatus 的接口实现)
public interface IRecordStatus
{
int RecordStatusTypeId { get; set; }
RecordStatusType RecordStatusType { get; set; }
}
这里的目标是将.Where(RecordStatusTypeId != (int)RecordStatusTypes.Deleted) 之类的语句替换为.ActiveRecords() 之类的扩展方法
我可以使用以下扩展方法来完成此操作:
public static IQueryable<T> ActiveRecords<T>(this DbSet<T> entitySet)
where T : class, IRecordStatus
{
return entitySet.Where(e => e.RecordStatusTypeId != (int)RecordStatusTypes.Deleted);
}
*我有DbSet<T>、IQueryable<T>、ICollection<T>和IEnumerable<T>的扩展方法
这对于MyDbContext.Entities.Where(e => e.RecordStatusTypeId != (int)RecordStatusTypes.Deleted) 之类的语句非常有效,但如果我尝试替换以下内容,则会收到错误“LINQ to Entities 无法识别该方法”:
MyDbContext.Entities.Where(e => e.RelatedEntity.Where(re => re.RecordStatusTypeId != (int)RecordStatusTypes.Deleted));
我想做的事:
MyDbContext.Entities.Where(e => e.RelatedEntity.ActiveRecords().Any());
如何更改我的扩展方法(或添加表达式),以便过滤 DbSet 以及 linq 子句内的相关实体上的活动记录?
【问题讨论】:
-
Entity Framework Plus 可以做到这一点:github.com/zzzprojects/EntityFramework-Plus
-
@CyrilIselin,谢谢,我去看看。
-
您的方法无法转换为 T-SQL,Linq to Entities 无法识别。将
AsEnumerable添加到您的Entities并重试:MyDbContext.Entities.AsEnumerable().Where...。 -
AsEnumerable 会将所有实体从数据库存储中拉到内存中。对于任何大型商店,您都不想这样做。
标签: c# entity-framework linq linq-to-entities entity-framework-6