有没有办法从子集合中定义默认顺序列?在我的例子中,我有一个 Form 实体,它有一个名为 FormItems 的 FormItem 实体集合。 FormItem 有一个名为 DisplayOrder (int) 的属性。我想确保我从方法返回的任何 Form 实体都正确排序了该集合。有没有办法在返回结果之前执行此操作?
例如,我试过这个但列表实际上没有排序:
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;
有没有不使用 DataLoadOptions 的方法来做到这一点?
最佳答案
试试这个:
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
方法对子项目进行排序。
关于c# - Linq to SQL 有序子集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2601704/