Jun Zheng
Jun Zheng

Reputation: 677

Generic Method for retrieving an entity model

I'm trying to create a generic method to retrieve a entity model. So what I'm trying to create a method that have the ability to take an entity model type and return the data of that type.

Here's what I've have so far.

        public List<T> Generic<T>(List<T> users) where T : List<T>, new()
    {
        using (var entities = new TestDBEntities())
        {
            var enUsers = entities.Users; // How to replace this to make it generic?
            return enUsers.ToList();
        }
    }

Thanks!

Upvotes: 2

Views: 784

Answers (3)

Kelly Cline
Kelly Cline

Reputation: 2246

If you don't like to use Reflection, this is an alternative:

TestDBEntities is a partial class, so you can add something like this to it:

private Dictionary<Type, ObjectQuery> m_ObjectSets;
private Dictionary<Type, ObjectQuery> ObjectSets
{
    get
    {
        if( m_ObjectSets == null )
        {
            m_ObjectSets = new Dictionary<Type, ObjectQuery>( );
            m_ObjectSets[ typeof( YourTypeA ) ] = YourObjectSetA;
            m_ObjectSets[ typeof( YourTypeB ) ] = YourObjectSetB;
            ...
        }
        return m_ObjectSets;
    }
}

and then

    public ObjectSet<T> GetObjectSet<T>( ) where T : class
    {
        return ( ObjectSet<T> ) ObjectSets[ typeof( T ) ];
    }

Your calling class then can have

return entities.GetObjectSet<T>( );

Upvotes: 1

Kelly Cline
Kelly Cline

Reputation: 2246

Are you using version 4.1 or later (which has DbContext)?

If not, or entities is ObjectContext, you can find the ObjectSet via Reflection, something like this:

var objectSet = entities.GetType( ).GetProperties( )
    .Where( p => p.PropertyType.IsGenericType 
         && p.PropertyType.GetGenericArguments( )[ 0 ].Name == typeof( T ).Name )
    .Select( p => p.GetValue( entities, null ) as ObjectSet<T> )
    .First( );
return objectSet.ToList( );

Upvotes: 3

tbddeveloper
tbddeveloper

Reputation: 2447

You can request entities from a DbContext via the Set<>() method. So, in this case I think you can get;

entities.Set<T>();

Upvotes: 1

Related Questions