Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...