【问题标题】:The specified type member is not supported in LINQ to Entities. Using 0 to many relationship for an entity propertyLINQ to Entities 不支持指定的类型成员。对实体属性使用 0 对多关系
【发布时间】:2014-12-03 17:45:09
【问题描述】:

我实际上是在尝试在名为“Report”的实体上创建一个扩展属性,它也可以在 LINQ 表达式中使用。

每个报告实体都与一个名为 ReportStatus 的表存在 0 对多关系,该表将包含每个报告的所有状态更新的历史记录。新报告将不包含此表中的条目(因此我将只返回空字符串)。我希望能够轻松获取任何给定报告的 current 状态代码(ReportStatus 中的最新条目),以及查询与我想要过滤的任何状态匹配的报告。由于涉及到 0 对多的关系,我无法找到一个干净的解决方案。如果有人可以提供一些指导,将不胜感激。

目前的扩展属性:

public partial class Report
{
    public string CurrentStatus
    {
        get
        {
            return
                this.ReportStatus.Count == 0 ?
                "" :
                this.ReportStatus.OrderByDescending(r => r.ReportStatusDate).First()
                .StatusCode;
        }
    }

它给出“LINQ to Entities 不支持指定的类型成员。仅支持初始化程序、实体成员和实体导航属性。”关于_repository.Reports.Where(r => r.CurrentStatus == StatusCodes.Pending).ToList()等表达式

【问题讨论】:

  • 它给了你错误,因为 LINQ-to-Entities 不知道如何翻译 CurrentStatus 的使用,因为它实际上不是数据库中的列。

标签: c# linq entity-framework linq-to-entities


【解决方案1】:

正如我在上面的评论中提到的,您实际上不能在 LINQ-to-Entities 中执行该查询,因为 CurrentStatus 实际上并不是数据库中的列。因此,您需要执行以下查询来获得您所要求的内容:

var pendingReports = _repository.Reports.Where(r => r.ReportStatus.Any() && 
                                               r.ReportStatus.OrderByDescending(s =>                        
                                                   s.ReportStatusDate).First().StatusCode == StatusCodes.Pending);

【讨论】:

  • 谢谢。我发布了我的想法。
【解决方案2】:

从 IronMan84 中吸取了一些教训,这就是我现在所拥有的。

做了一个扩展类:

public static class QueryExtensions
{
    public static IQueryable<Report> GetByStatus(
    this IQueryable<Report> query, string statusCode)
    {
        if (statusCode == "")
        {
            return query.Where(r => r.ReportStatus.Count == 0); // new reports, no status history
        }
        else
            return query.Where(r => r.ReportStatus.OrderByDescending(s =>
                   s.ReportStatusDate).FirstOrDefault().StatusCode.StatusCode1 == statusCode);
    }
}

并像这样使用它:

         _repository.Reports.GetByStatus(StatusCode.Pending)ToList();

当我只需要查看一个单独实体的状态时,我仍然可以使用我的问题中显示的 CurrentStatus 扩展属性。谢谢!

【讨论】:

    猜你喜欢
    • 2015-01-27
    • 2012-07-17
    • 1970-01-01
    • 2020-08-15
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多