2

次のクエリでコレクションを取得します。

var numbers = _betDetailItem.GetBetDetailItems().Where(betDetailItem => betDetailItem.BetDetail.Bet.DateDrawing == resultToCreate.Date && betDetailItem.BetDetail.Bet.Status == 1).Where(condition);

そこで、ナビゲーション プロパティにアクセスし、バインドされた情報をナビゲートできます。それらを実際に使用してデータをフィルタリングする方法に注意してください。

結果をグループ化すると、ナビゲーション プロパティが null になります。

var grouped = numbers.GroupBy(p => p.BetDetail.Bet);
//Iterate through the collection created by the Grouping
foreach (IGrouping<Bet, BetDetailItem> group in grouped)
{
    var details = group.Key.BetDetails; //This is what doesn't work. BetDetails is a navigation property which was accessible in the previous query. 
}

私は何か間違ったことをしていますか?

4

2 に答える 2

1

を実行するGroupBy()と、もはやエンティティを扱っているわけではありません。それらは...まあ、グループ化されているので、varinvar grouped = ...はタイプになりIEnumerable<IGrouping<...ました。groupedそのため、コレクション内のアイテムで使用できるメソッドは、IGrouping<>インターフェイスのメソッドです。

OrderBy()必要に応じての代わりにを使用することもGroupBy()、2 つのレベルで反復する必要がある場合もありますgrouped

特定の 内に入ると、IGrouping<>探しているプロパティにアクセスできるはずです。

于 2010-02-11T20:27:59.323 に答える
1

You are confusing LINQ to Entities and object operations.

This is LINQ to Entities:

var numbers = _betDetailItem.GetBetDetailItems().Where(betDetailItem => betDetailItem.BetDetail.Bet.DateDrawing == resultToCreate.Date && betDetailItem.BetDetail.Bet.Status == 1).Where(condition);

So is this:

var grouped = numbers.GroupBy(p => p.BetDetail.Bet);

These are object operations:

foreach (IGrouping<Bet, BetDetailItem> group in grouped)
{
    var details = group.Key.BetDetails; //This is what doesn't work. BetDetails is a navigation property which was accessible in the previous query. 
}

In LINQ to Entities, there is never any need to think about loading related instances. You can always refer to any property of any object. However, at some point, you want to move out of the LINQ to Entities world and into object space, because you want to work with instances of type BetDetail instead of type IQueryable<BetDetail>. This means that the Entity Framework is now required to generate SQL to retrieve data from the database. At that point, it doesn't snow which related instances you will be accessing in your code later on. Nothing in your LINQ to Entities query forces the loading of the related Bet. So unless you do something to cause it to be loaded, like use eager loading, explicit loading, or EF 4 lazy loading, it won't be loaded.

Using lazy loading (e.g., in Entity Framework 4, or in another ORM) will make this code appear to function, but it will be unnecessarily slow, due to the large number of database queries generated. A better solution would be to use eager loading or projection. This way there will be only one DB roundtrip.

于 2010-02-12T18:14:47.503 に答える