Reputation: 1033
I have 2 tables in a DB with very similar schemas that need to be queried in similar ways. I created a partial class for the linq entities, and then made the classes implement an interface, IEvent which defines all the properties with matching signatures that I need. All is good with that, I can cast my results to IQueryable and use the same code to work on data from more than one source. What I cannot figure out is a nice way to get the Table based on whatever "DataSource" (i.e. event table) is currently active, so currently I have this nasty switch statement that will need updating if another data source gets added and I don't like it one bit. Anyone got any smart ideas, it is late here and my brain is failing... :-S
The code goes something like this:
private IQueryable<IEvent> getEvents(IEnumerable<int> IDs)
{
var db = new EventDataContext();
// activeDataSource is an enum defined elsewhere
switch (activeDataSource)
{
case DataSource.Source1:
return db.Events1.Where(e => IDs.Contains(e.ID)).Cast<IEvent>();
break;
case DataSource.Source2:
return db.Events2.Where(e => IDs.Contains(e.ID)).Cast<IEvent>();
break;
}
}
Upvotes: 3
Views: 1506
Reputation: 43087
I would suggest making the method generic and using DataContext.GetTable():
private IQueryable<IEvent> getEvents<T>(IEnumerable<int> IDs)
where T : class, IEvent
{
var db = new EventDataContext();
return db.GetTable<T>.Where(e => IDs.Contains(e.ID)).Cast<IEvent>();
}
Upvotes: 4