Reputation: 342
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?
Upvotes: 3
Views: 4981
Reputation: 9162
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.
Upvotes: 0