I was tinkering around to figure out a way to unify a data access layer for some databases which have types that are identical field wise but reside in different EF DB contexts. I came up with something like this (plz ignore the string interpolation, this is just a prototype):
public static T FetchEvent<T>(System.Data.Entity.DbContext dbContext, int eventId) where T : class, IEvent
{
var record = dbContext.Database.SqlQuery<T>($"SELECT * FROM Events WHERE EventId = {eventId}").SingleOrDefault();
return record;
}
Each database has an Events table and the related EF entities implement IEvent, where IEvent is just the fields and their data types to mimic the table structure. With the generic T parameter, it's left up to the calling code to specify the proper local EF entity type when retrieving records.
The code runs and returns records however the EF context on the dynamic proxy object is null, so you can't make any updates to the entities.
My question: is there a way to get the EF context to persist when I am retrieving records in this fashion?