Reputation: 2736
I use Net Core 1.1 and Entity Framework Core with the fluent API. I am writing a simple extension method for DbSet to show its entities in Console:
public static class DbSetExtension
{
public static void Show<T>(this DbSet<T> set) where T:class
{
WriteLine();
WriteLine($"Set: {typeof(T).Name} - {set.Count()} objects.");
WriteLine();
foreach (var e in set)
{
WriteLine(e);
}
WriteLine();
WriteLine();
}
}
This works but I'd like to have the entities sorted by the primary key before showing them. If I had the DbContext
it would have been easily accomplished by doing something like this:
var entityType = db.Model.FindEntityType(typeof(T));
var primaryKeyName = entityType.FindPrimaryKey().Properties.First().Name;
var set = db.Set<T>();
var orderedEntities = (set.OrderBy(e=> e.GetType().GetProperty(primaryKeyName).GetValue(e,null))).ToList();
Is there a way to get the same result starting from the DbSet
?
Upvotes: 5
Views: 4237
Reputation: 205849
It's possible, but not "officially" - you have to use some methods marked as This API supports the Entity Framework Core infrastructure and is not intended to be used directly from your code. This API may change or be removed in future releases..
You basically utilize the fact that DbSet<T>
implements IInfrastructure<IServiceProvider>
, so you can obtain IDbContextServices
via GetService
method in order to get the model from Model
property:
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
...
var model = set.GetService<IDbContextServices>().Model;
var entityType = model.FindEntityType(typeof(T));
var properties = entityType.GetProperties();
var primaryKeyName = entityType.FindPrimaryKey().Properties.First().Name;
var sortedSet = (set.OrderBy(e=> e.GetType().GetProperty(primaryKeyName).GetValue(e,null))).ToList();
...
Upvotes: 5