Is there a way to force SortOrder on Related Data in Entity Framework?

断了今生、忘了曾经 提交于 2019-12-11 04:34:50

问题


Assuming that I have an EF Code-First implementation with the following simplified scenario:

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 data:

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

Is there a way to force FormQuestionMappings to be loaded by their SortOrder and not by their default location?


回答1:


Yes, it's possible. Entity Framework accepts all collections, that implements ICollection interface. So, you can use your own collection, that is sorded in any way you want. EF materialize collections via Add method calls on ICollection interface. So, something like this should work:

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


来源:https://stackoverflow.com/questions/43926462/is-there-a-way-to-force-sortorder-on-related-data-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!