0

Is this example bad practice because it make several database calls?

Is it any way I can make this to one DB call? Like use 'where' instead of 'firstOrDefault' and compare FlagDate with each date on the message in my messageList?

foreach (var message in messageList)
{
    var dayFlag = db.DayFlags.FirstOrDefault(x => 
                                    x.FlagDate == message.MessageDate);
}
4

2 回答 2

4

If you want to retrieve only the dayFlags which a corresponding Date to the messageList, you need to extract the dates first in a separate list, then pass it to a Linq To Sql query.

Note that to retrieve only the first DayFlags of each Date, you need to group the flags by date.

var dates = messageList.Select(m => m.MessageDate).ToList();
var dayFlags = db.DayFlags.GroupBy(flag => flag.FlagDate)
                          .Where(group => dates.Contains(group.Key))
                          .Select(group => group.First());
于 2013-10-10T09:02:53.767 回答
0

这是 linq 的解决方案:

var dates = messageList.Select(m => m.MessageDate).ToList();
var dayFlags = from df in db.DayFlags
               where dates.Contains(df.FlagDate)
               select df;
于 2013-10-10T11:59:06.900 回答