Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / .NET

Determine the Entity Set for a given Entity.

4.89/5 (2 votes)
19 Oct 2010CPOL 9.5K  
I am writing a generic repository and got stuck on the List<t>() method, as I didn't have any entity set name. Normally you can glean this from an entity instance, like in an Update<t>() method, but List<t>() has no starting point. I deduced the following method to determine the Type of an entity set object that contains entities of type T, which is the type parameter of my repository object.

C#
private static string GetEntitySetName(FoodEntities context)
{
    var entitySetType = context.GetType().GetProperties().Where(
        p =>
        p.PropertyType.IsGenericType && p.PropertyType.Name.StartsWith("ObjectSet") &&
        p.PropertyType.GetGenericArguments()[0].Name == typeof (T).Name).Single();
    return entitySetType.Name;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)