Linq to SQL ordered kids collection

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

For example, I tried this, but the list is not really 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?

+3
source share
5 answers

Try the following:

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

, , DataLoadOptions.AssociateWith.

+1

, FormItems PrivateFormNames .

:

partial class Form
{
    public IQueryable<FormItem> FormItems
    { 
        get { return PrivateFormItems.OrderBy(x => x.DisplayOrder); } 
    }
}

, ... - : Derived Form linq digram , Form ( ).

FormItems :

 partial class FormDerived
    {
        public override IQueryable<FormItem> FormItems
        { 
            get { return base.FormItems.OrderBy(x => x.DisplayOrder); } 
        }
    }

linq . , , context.FormItems.

0

Form , FormItems.

partial class Form
{
    public IQueryable<FormItem> OrderedFormItems
    { 
        get { return FormItems.OrderBy(x => x.DisplayOrder); } 
    }
}
0

:

var form2 = form.FormItems.OrderBy(x => x.DisplayOrder); return form2;

0

:

public static class FormExtensions
{
        public static IQueryable<FormItem> GetOrderedItems(this Form form)
        {
                // without lazy loading, but you have to get current context somehow
                return CurrentContext.FormItems.Where(x => x.FormId == form.Id).OrderBy(x => x.DisplayOrder);

               // with lazy loading
               return form.FormItems.OrderBy(x => x.DisplayOrder);
        }
}

0

Source: https://habr.com/ru/post/1740349/


All Articles