A Reason for Non-deferred LINQ Statement

Someone (two people, actually) asked on StackOverflow.com why someone would want to force a LINQ statement to execute immediately rather than allowing deferred execution. Since I can’t respond to the comments yet, I’ll explain here.


In my present application, I need to aggregate based upon properties of a type that is created based upon one of the fields in a record. An example (because that statement was barely intelligible even to me) would be:

A database field contains EVENTNAME-PORTION-OTHERCODE. I have a class that splits out EVENTNAME (after figuring whether PORTION is before or after OTHERCODE and allowing for EVENTNAMEs that also contain dashes).

I need to do a GroupBy() based upon EVENTNAME, but LINQ (I’m using LINQ-to-Entities) does not allow me to send in a type to SQL Server for aggregating. Thus the following fails:

IEnumerable<EventAgg> agg = ctx.Events.GroupBy(e =>
  new { w.EventCode.EventName }
);

I must instead do the following:

IEnumerable<EventAgg> agg = ctx.Events.ToList().GroupBy(e =>
  new { w.EventCode.EventName }
);

N.B.: For this, I have created a partial class Event with an EventCode property. The setter for EventCode has the parsing code to pull apart the drek in the table field:

public partial class Event {
  public EventCode EventCode { get; set; }
}
 
public class EventCode {
  private string _eventCode;
  public string EventCode {
    get { return _eventCode; }
    set {
      _eventCode = value;
      ParseEventCode(); // sets other properties
    }
  }
  public string EventName { get; }
  public string Portion { get; }
  public string OtherCode { get; }
}

About pyrolupus

Writer, father, teacher, programmer, performer. And I make some mean pancakes, too.
This entry was posted in .Net and tagged , , . Bookmark the permalink.

Comments are closed.