Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query all tables that implement an interface

I have implemented an interface for some of my entity classes:

public partial class Order : IReportable
{
   public string TableName { get { return "Order"; } }
}

public partial class Client: IReportable
{
 public string TableName { get { return "Client"; } }
}


public interface IReportable
{
    string TableName { get; }
}

Then I added this to the DbContext:

public virtual DbSet<IReportable> IReportable { get; set; }

When I try to query all the tables that implement this interface (as shown here):

var result = from reportabletable in db.IReportable
             where reportabletable.TableName == table_name
            select reportabletable

I get the following exception:

The type 'Report.DataAccess.IReportable' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive or generic, and does not inherit from EntityObject.

like image 499
enb081 Avatar asked Oct 15 '14 14:10

enb081


1 Answers

I would go for something like this:

Create this extension method

public static class DbContextExtensions
{
    public static IEnumerable<T> SetOf<T>(this DbContext dbContext) where T : class
    {
        return dbContext.GetType().Assembly.GetTypes()
            .Where(type => typeof(T).IsAssignableFrom(type) && !type.IsInterface)
            .SelectMany(t => Enumerable.Cast<T>(dbContext.Set(t)));
    }
}

And use it like this:

using (var db = new dbEntities())
{
 var result = from reportabletable in db.SetOf<IReportable>()
         where reportabletable.TableName == table_name
        select reportabletable
}
like image 91
natenho Avatar answered Sep 20 '22 16:09

natenho