Question

I need to execute a dynamic set type, here's what I'm trying to do (pseudo):

var type = GetSetType(); //System.Type
var set = context.Set(type);
var results = set.ToArray();

I know this can't work for sure, Enumerable ex. methods are only for generic IEnumerables, but I tried set.AsQueryable().Cast<object>().ToArray(), and a NotSupportedException was thrown: "LINQ to Entities only supports casting EDM primitive or enumeration types.".

Any way to execute a non-generic DbSet?

Was it helpful?

Solution

I should have deleted my question since the answer is too simple, but for the record, let's just keep it up.

namespace System.Linq
{
  public static class EntityFrameworkExtensions
  {
    public static IEnumerable<object> AsEnumerable(this DbSet set)
    {
      foreach (var entity in set)
        yield return entity;
    }
  }
}

Usage:

var collection = context.Set(entityType).AsEnumerable();

Beware that any filtering performed on the retuned collection will not happen on the SQL server, but on the collection enumerator, the entire table will be returned. Use only when loading all rows anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top