Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

c# - EF core set default OrderBy to a List property in the parent entity

I need an attribute or a fluent method to set the default OrderBy to a property to avoid to have to add the OrderBy clause each time I use an Include.

public class ItemsGroup : BaseEntity
    {
        public virtual List<ItemDefinition> ItemDefinitions { get; set; }
        ...
    }
public class ItemDefinition: BaseEntity
    {
        ...
        public int Position { get; set; }
    }

I want to add an attribute like that

[DefaultOrderBy(nameof(ItemDefinition.Position), Sorting.Asc)]
public virtual List<ItemDefinition> ItemDefinitions { get; set; }

or something like that :

modelBuilder.Entity<ItemsGroup>().Property(ig => ig.ItemDefinitions).DefaultOrderBy(id => id.Position, Sorting.Asc);

I saw some interesting workaround like this for EF with interceptors and visitors but I can't reproduce it with EF core.

Is there a way to do something like that with EF core?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Am not aware that you can do this directly.

Perhaps an extension method:

public static IList<ItemDefinition> SortedByPosition(this IList<ItemDefinition> list)
{
    return list.OrderBy(i => i.Position);
}

Use:

foreach (var ItemDefinition in myDefinitionList.SortedByPosition())
{
    // use itemDefinition
}

Or, if you want them sorted at source, the following should work:

public class ItemsGroup
{
    [NotMapped]
    private IList<ItemDefinitions> _itemDefinitions;

    public IList<ItemDefinitions> ItemDefinitions
    {
        get => _itemDefinitions;
        set
        {
            _itemDefinitions = value.OrderBy(i => i.Position);
        }
    }
}

Then they're sorted from the get go.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...