Entity framework – get entity by name

You can do it using reflection, however you will also need to use generics because the type of list returned by the ToList() method is different for each entity type.

You can access a property getter through reflection like so:

var enumerable = typeof([ClassNameOfContext]).GetProperty(name).GetValue(ctx, null);

Whereas [ClassNameOfContext] is the name of the class that ctx is an instance of. This is not obvious from your code, but you know it 🙂

The problem is that enumerable will be an object and has to be casted to IEnumerable<EntityType> where EntityType is the type of entity you are accessing. In other words, it depends on the name you are passing. If you use generics to determine the type, you will be able to properly cast the object and don’t have to return a dynamic even.

public TEntity Get<TEntity>(string name)
{
    ...

and transform the line from above:

var enumerable = (IEnumerable<TEntity>)(typeof([ClassNameOfContext]).GetProperty(name).GetValue(ctx, null));
return enumerable.ToList();

here you go!

Addendum: You could, conceivably, get rid of the string parameter, too – having names of types or properties in strings should be avoided where possible because it is not type safe. The compiler does not recognize it, and IDE features such as refactorings don’t account for it. The problem here is that the property names are usually the pluralized form of the entity type names. But you could use reflection to find the property whose type matches the TEntity. I leave this as an exercise 🙂

Leave a Comment