I have a table, lets call it Record. Containing:
ID (int)
CustID (int)
Time (datetime)
Data (varchar)
I'm using Entity Framework 4, with Connector .Net 6.4.3, using C#4.0 in VS 2010.
I need the latest (most recent) record for each customer:
SQL version: select * from record as i group by i.custid having max(id);
LINQ version 1:
from g in ee.Records group g by g.CustID into grp select grp.LastOrDefault()
throws an error:
System.NotSupportedException was unhandled by user code
Message=LINQ to Entities does not recognize the method 'Faizan_Kazi_Utils.Record LastOrDefault[Record ](System.Collections.Generic.IEnumerable`1[Faizan_Kazi_Utils.Record ])' method, and this method cannot be translated into a store expression.
Source=System.Data.Entity
LINQ version 2:
var list = (from g in ee.Records group g by g.CustID into grp select grp).ToList();
Record[] list2 = (from grp in list select grp.LastOrDefault()).ToArray();
dgvLatestDistinctRec.DataSource = list2;
This works, but is inefficient because it loads ALL records from the database into memory and then extracts just the last (most recent member) of each group.
Is there any LINQ solution that approaches the efficiency and readability of the mentioned SQL solution?
ID (int)
CustID (int)
Time (datetime)
Data (varchar)
I'm using Entity Framework 4, with Connector .Net 6.4.3, using C#4.0 in VS 2010.
I need the latest (most recent) record for each customer:
SQL version: select * from record as i group by i.custid having max(id);
LINQ version 1:
from g in ee.Records group g by g.CustID into grp select grp.LastOrDefault()
throws an error:
System.NotSupportedException was unhandled by user code
Message=LINQ to Entities does not recognize the method 'Faizan_Kazi_Utils.Record LastOrDefault[Record ](System.Collections.Generic.IEnumerable`1[Faizan_Kazi_Utils.Record ])' method, and this method cannot be translated into a store expression.
Source=System.Data.Entity
LINQ version 2:
var list = (from g in ee.Records group g by g.CustID into grp select grp).ToList();
Record[] list2 = (from grp in list select grp.LastOrDefault()).ToArray();
dgvLatestDistinctRec.DataSource = list2;
This works, but is inefficient because it loads ALL records from the database into memory and then extracts just the last (most recent member) of each group.
Is there any LINQ solution that approaches the efficiency and readability of the mentioned SQL solution?