Tomasz Gawlik
Tomasz Gawlik

Reputation: 333

Get list of entity objects by generic T which is type of EntityObject

I'm using EF 4 and I want to create generic method, which will allow me to load data from tables with only two columns - which I am sure exists in every table and entity. My problem is that I don't know how to get list of entities only knowing type of entity.

    Dictionary<long, string> GetList<T>() where T : System.Data.Objects.DataClasses.EntityObject
    {
        Dictionary<long, string> list = new Dictionary<long, string>();

        //var entityList = this.context.GetEntitiesByType(T);
        //
        foreach (var entity in entityList)
        {
            list.Add(typeof(T).GetProperty("Id").GetValue(entity, null),
                     typeof(T).GetProperty("Name").GetValue(entity, null))
        }
        return list;
    }

Is it possible to obtain this list ? As a workaround I could get table name by using method

    dbContext.GetTableName<T>();

and try to execute sql query, but it seems like bad idea. Any thoughts ?

Upvotes: 1

Views: 1674

Answers (1)

afnpires
afnpires

Reputation: 619

You should use CreateObjectSet< T >() which returns a ObjectSet< T >.

Usage:

context.CreateObjectSet<T>()

For more information http://msdn.microsoft.com/en-us/library/dd382944(v=vs.100).aspx

Upvotes: 1

Related Questions