Tx3
Tx3

Reputation: 6916

Using same query for different DbSets in Entity Framework

I have two different views to the same database table and I would like to use same query against both views.

I have now following ugly solution where I have basically copy of the query.

DbSet<uvw_MyView1> view1 = entities.uvw_MyView1;
DbSet<uvw_MyView2> view2 = entities.uvw_MyView2;

if(doQueryOnView1)
{
    // huge query
    view1.Where(jada jada)
}
else
{
    // huge query copied here with exception of different DbSet
    view2.Where(jada jada)
}

What I would like to have is more elegant solution. Basically I want to have same query part for two DbSet's that are in column wise exactly same, but those return different rows. Any ideas?

Upvotes: 1

Views: 806

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

Add interface containing all properties of your view and implement this interface by both view entities. After that create method containing whole your query:

public static IQueryable<T> YourHugeQueryMethod<T>(DbContext context, ...) 
     where T : class, IView, new()
{
    DbSet<T> set = context.Set<T>();
    return set.Where(...);
}

Upvotes: 1

Related Questions