0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

同じID内で最大のものを表示するときのEntityFramework

Posted at

SQLDatabaseでシステム運用していたが、処理が遅くてエラーになってしまった。
クエリはこんな感じ

C#

var query = context.TBL_A.GroupBy(p => p.Type).Select(g => g.OrderByDescending(p => p.Date)
.FirstOrDefault()

出典
https://stackoverflow.com/questions/16273485/entity-framework-select-one-of-each-group-by-date

TBL_Aに対してType列でGroupByして、日付の降順に並び替え、FirstOrDefaultで1行目を取得します。これにより、同一値内の最大日付のレコードのみ取得することができます。
SQLDatabase、Basicプランで運用していましたが、対象テーブルが5000レコードを超えたくらいでタイムアウトエラーが発生してしまいました。30秒以上返ってこないでやんの。。

なので、修正してみました。

C#

var query = context.TBL_A.Wherey(x => !context.TBL_A.Any(s => s.Type == x.Type && s.Date > x.Date))


参考
http://labs.timedia.co.jp/2014/10/selecting-max-record-in-group-by.html

 
条件は同一のTypeかつDateが小さいもの。!context.TBL_A.Any でNot Exists句になるので、一番大きいものだけが取得できます。素晴らしい。

パフォーマンスも秒でかえってくるようになりました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?