LINQ to Entities 无法识别该方法,且该方法无法转换为 store 表达式

1 c# linq asp.net-mvc linq-to-entities entity-framework

我有一个包含填充私有字段的函数的类,就像这样......

public class ActionPlan
{
    [Key, Column(Order=0)] 
    public long EnterpriseID  { get; set; }

    [Key, Column(Order=1)]
    public Guid  ActionPlanID { get; set; }

    private ActionPlanCategory _category;
    public ActionPlanCategory GetCategory()
    {
        // Get data and initialize _category
    }
}
Run Code Online (Sandbox Code Playgroud)

在一个视图中,我试图遍历一个由IEnumerable<ActionPlan>. 但是一旦 foreach 循环开始,我就会收到 GetCategory() 函数的上述错误。LINQ to Entities 中没有映射函数,所以我真的不明白问题是什么。我的视图看起来像......

@model IEnumerable<ActionPlan>

@foreach (var actionPlan in Model)
{
    <tr>
        <td class="sortable_data"><a href="#" class="jumpToMyActionPlans protected" data-plan_key="@actionPlan.Key">@actionPlan.Name</a></td>
        <td class="sortable_data">@(actionPlan.GetCategory() == null ? "NA" : actionPlan.GetCategory().ActionPlanCategoryDescription)</td>
        <td class="sortable_data" style="vertical-align: middle;"><b>@(actionPlan.GetStatus() == null ? "NA" : actionPlan.GetStatus().ActionPlanStatusDescription)</b></td>
        <td>@actionPlan.DescriptionEventCondition</td>
        <td>@actionPlan.ExpectedImpactOutcome</td>
        <td class="sortable_data">@actionPlan.LeadBy</td>
        <td class="sortable_data">@actionPlan.FormattedDeadlineString</td>
    </tr>
}
Run Code Online (Sandbox Code Playgroud)

请注意,一旦输入 foreach 的条件,在执行实际到达此行之前,就会抛出错误:

<td class="sortable_data">@(actionPlan.GetCategory() == null ? "NA" : actionPlan.GetCategory().ActionPlanCategoryDescription)</td>
Run Code Online (Sandbox Code Playgroud)

Nat*_*n A 5

基于该错误,我假设 LINQ to Entities 用于提取数据,并且GetCategory()在将其发送到数据库之前以某种方式在查询中使用。如果是这样,那将是你的问题。

为避免这种情况,您需要将其从查询中提取出来并在进行 SQL 调用后使用该方法。

不好的例子:

var qry = SomeContext.SomeTable.OrderBy(x => x.GetCategory().SomeMember);
Run Code Online (Sandbox Code Playgroud)

使固定:

var qry = SomeContext.SomeTable.ToList().OrderBy(x => x.GetCategory().SomeMember);
Run Code Online (Sandbox Code Playgroud)

该修复强制在通过自定义方法排序之前进行 SQL 调用。