c# - 有没有办法在 Entity Framework 中强制对相关数据进行排序?

标签 c# entity-framework entity-framework-6

假设我有一个具有以下简化场景的 EF Code-First 实现:

public class Form{
    [key]
    int FormID {get;set;}
    int Name {get;set;}

    public virtual ICollection<FormAndQuestionMapping> FormQuestionMappings
    {
        get;
        set;
    }
}

public class FormAndQuestionMapping{
    [ForeginKey]
    int FormID {get;set;}

    [ForeginKey]
    int QuestionID {get;set;}

    int SortOrder {get; set;}

    public virtual Form Form { get; set; }
    public virtual Question Question { get; set; }
}

FormAndQuestionMapping 数据:

 FormID | QuestionID | SortOrder
   1    |     1      |     5
   1    |     2      |     20
   1    |     3      |     10
   1    |     4      |     15

有没有办法强制 FormQuestionMappings 按其 SortOrder 而不是按其默认位置加载?

最佳答案

是的,这是可能的。 Entity Framework 接受所有实现 ICollection 接口(interface)的集合。因此,您可以使用自己的集合,该集合可以按照您想要的任何方式排序。 EF 通过 ICollection 接口(interface)上的 Add 方法调用来具体化集合。所以,像这样的东西应该有效:

public class Form
{
    private ICollection<FormAndQuestionMapping> _formQuestionMappings;

    public Form()
    {
        _formQuestionMappings = new SortedSet<FormAndQuestionMapping>(new Comparer());
    }

    private class Comparer : IComparer<FormAndQuestionMapping>
    {
        public int Compare(FormAndQuestionMapping x, FormAndQuestionMapping y)
        {
            return x.SortOrder - y.SortOrder;
        }
    }

    [key]
    int FormID { get; set; }
    int Name { get; set; }

    public virtual ICollection<FormAndQuestionMapping> FormQuestionMappings
    {
        get { return _formQuestionMappings; }
        set { _formQuestionMappings = value; }
    }
}

public class FormAndQuestionMapping
{
    [ForeginKey]
    int FormID { get; set; }

    [ForeginKey]
    int QuestionID { get; set; }

    public int SortOrder { get; set; }

    public virtual Form Form { get; set; }
    public virtual Question Question { get; set; }
}

关于c# - 有没有办法在 Entity Framework 中强制对相关数据进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43926462/

相关文章:

c# - 具有通用扩展方法的 AutoMapper 映射

c# - 如何让datagridview在离开一行时自动保存记录

entity-framework - 自创建数据库以来,支持 'myDBContext' 上下文的模型已发生更改。考虑使用 Code First 迁移来更新数据库

linq - 如何使用 DbContext 使用 linq to EF 删除多行数据

c# - MVC 脚手架和 EF 'One To Zero or One' 关系错误

c# - C# 可以让我的类看起来像另一个类吗?

c# - 如何阻止我的 <httpErrors> 404 "ExecuteURL"映射破坏我的表单?

c# - 将存储过程 PIVOT 表转换为 LINQ 查询

asp.net-core - System.MissingMethodException : Method not found: 'UInt32 Npgsql. NpgsqlStatement.get_Rows()

c# - 使用 EF Code First 建模员工-助理关系