Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL ordered child collection

Tags:

c#

linq-to-sql

Is there a way to define a default order column from a child collection? In my case, I have a Form entity that has a collection of FormItem entities called FormItems. FormItem has a property called DisplayOrder (int). I want to make sure that any Form entities I return from a method have that collection properly ordered. Is there a way to do this before returning the result?

For example, I tried this but the list is not actually sorted:

var form = context.Forms.FirstOrDefault(x => x.IsDeleted == false && x.FormName == formName);
if (form != null)
{
    form.FormItems.OrderBy(x => x.DisplayOrder);
    // I can't even figure out a way to cast this next line so that it will compile
    // form.FormItems = form.FormItems.OrderBy(x => x.DisplayOrder);
}
return form;

Is there a way to do this without using DataLoadOptions?

like image 407
Matt Connolly Avatar asked May 21 '26 15:05

Matt Connolly


1 Answers

Try this:

DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.LoadWith<Form>(f => f.FormItems);
loadOptions.AssociateWith<Form>(f => 
    f.FormItems
        .OrderBy(fi => fi.DisplayOrder);
);

context.LoadOptions = context;

var form = context.Forms
    .FirstOrDefault(x => 
        !x.IsDeleted &&
        x.FormName == formName
    );

meaning, ordering of child items made by DataLoadOptions.AssociateWith method.

like image 96
Oleks Avatar answered May 25 '26 10:05

Oleks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!