c# - Linq to SQL 有序子集合

标签 c# linq-to-sql

有没有办法从子集合中定义默认顺序列?在我的例子中,我有一个 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/

相关文章:

C#/XNA 对比。 java/vector 用于简单的游戏开发

c# - 调整翻转和旋转图像的大小

c# - LINQ 到 SQL : Check for existence of a generic entity in a generic Repository

c# - 如何使用 LINQ 匹配两个相同的数据库表?

c# - 在 Visual studio 2015 中,设计器以 win 形式更改控件的属性,例如大小

c# - LINQ to SQL 其中 ID 不在 some_list 中

c# - DataContext.CreateDatabase() 说文件已经存在 - 但它不存在

.net - 在程序中使用 SQL 数据库的要求

c# - LINQ to SQL 从多对多表中选择完全匹配的记录

c# - 我如何保证 Ninject 会自动调用 Disposable()?