kob490
kob490

Reputation: 3317

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

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?

Upvotes: 2

Views: 112

Answers (1)

Backs
Backs

Reputation: 24913

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

Upvotes: 4

Related Questions