开发者

.NET Framework 3.5 EntityCollection OrderBy Question

开发者 https://www.devze.com 2023-01-23 15:59 出处:网络
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.

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();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号