2

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?

5
  • warning your code sets you up for potential sql injection Jan 4, 2022 at 16:13
  • what version of ef? Jan 4, 2022 at 16:13
  • @DanielA.White this is EF 6 Jan 10, 2022 at 0:41
  • does @Guru Stron answer solve your problem?
    – sa-es-ir
    Jan 10, 2022 at 7:08
  • @SaeedEsmaeelinejad yup :] Jan 10, 2022 at 16:57

1 Answer 1

3
+100

Since all events have the same fields which can be extracted to then interface and assuming that concrete T's are mapped to corresponding contexts you can just use the DbContext.Set<T> method:

public interface IEvent
{
    public int EventId {get; set;}
    // rest of the props 
}

public static T FetchEvent<T>(System.Data.Entity.DbContext dbContext, int eventId) where T : class, IEvent
{
    var record = dbContext
        .Set<T>()
        .Where(e => e.EventId == eventId)
        .SingleOrDefault();
    return record;
}
2
  • Thanks Guru, nailed it! Also did you write an earlier response about how you need to call Set<T>() to enable change tracking (since using a query without it has change tracking disabled)? Jan 10, 2022 at 17:01
  • 1
    Also important: if an underlying class is written in VB, you'll need to use the raw SQL query approach, otherwise the call fails with the The specified type member is not supposed by LINQ to entities error. I think this has to do with how VB implements interfaces, you have to explicitly handle them, whereas C# supports implicit handling. Jan 10, 2022 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.