Reputation:
I have a class which contains a function which populates a private field, like this...
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
}
}
In a view I'm trying to iterate through a Model consisting of an IEnumerable<ActionPlan>
. But as soon as the foreach loop begins I receive the above error for the GetCategory() function. Functions aren't mapped in LINQ to Entities, so I don't really understand what the problem is. My View looks something like...
@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>
}
Note that the error is thrown as soon as the condition for the foreach is entered, before execution actually reaches this line:
<td class="sortable_data">@(actionPlan.GetCategory() == null ? "NA" : actionPlan.GetCategory().ActionPlanCategoryDescription)</td>
Upvotes: 2
Views: 2381
Reputation: 11319
Based on the error, I assume that LINQ to Entities is being used to pull the data and that GetCategory()
is somehow being used in the query before it's sent to the database. If that's the case, that will be your problem.
To avoid it, you need to pull that out of the query and use that method after the SQL call is made.
Bad Example:
var qry = SomeContext.SomeTable.OrderBy(x => x.GetCategory().SomeMember);
Fix:
var qry = SomeContext.SomeTable.ToList().OrderBy(x => x.GetCategory().SomeMember);
The fix forces the SQL call to be made before ordering by the custom method.
Upvotes: 8