.NET Framework 3.5 EntityCollection OrderBy Question
I'm using .NET Framework 3.5 with ASP.NET MVC and I'm using Linq To Entity for my data objects.
I have a Promotion Object that has a 1 to many relat开发者_运维技巧ionship to the Location object.
What I want to do is take the collection of Locations from the Promotion object and sort those without putting them into another variable. Something like...
promotionEntity.Locations.OrderBy(l => l.Distance);
But it does nothing to the *.Locations collections. Is there a way that I can have that EntityCollection sorted how I need without putting it in another List or variable?
Thanks.
If the type of locations is IEnumerable you can just assign the result of OrderBy:
promotionEntity.Locations = promotionEntity.Locations.OrderBy(l => l.Distance)
If the type is something like List<Location>
then you will probably have to create a new List:
promotionEntity.Locations =
new List<Location>(promotionEntity.Locations.OrderBy(l => l.Distance));
One way is to use EntityCollection.CreateSourceQuery Method:
var promotionEntity = context.Promotions.First();
var sq = product.Locations.CreateSourceQuery().OrderBy(l => l.Distance);
promotionEntity.Locations.Attach(sq);
Or if you don't care about the resultant object's type can do projection inside an anonymous type:
var promotionEntity = context.Promotions.Select(p => new
{
p,
Locations = p.Locations.OrderBy(l => l.Distance)
}).First();
精彩评论