假设我有一个具有以下简化场景的 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/