How about using generic method that indicates entity not by name but by type instead? The result you may store as dynamic variable so that you will be able to access any property in it.
public string GetEntityByName<TEntity>(int id)
{
using (var context = new MyContext())
{
dynamic entity = context.Set<TEntity>.Find(id);
try
{
return entity.Name;
}
catch(Exception e)
{
// Handle the situation when requested entity does not have Name property
}
}
}
Alternatively you may use reflection to access Name property:
public string GetEntityByName<TEntity>(int id)
{
var nameProperty = typeof(TEntity).GetProperty("Name");
if(nameProperty == null)
return null;
using (var context = new MyContext())
{
object entity = context.Set<TEntity>.Find(id);
return nameProperty.GetValue(entity) as string;
}
}
The above methods you may use like that:
string name = GetEntityByName<Car>(id);
If you insist on having the entity type passed as string parameter you may achieve it as well:
public string GetEntityByName(int id, string entityName)
{
Type entityType = Type.GetType(entityName);
var nameProperty = entityType.GetProperty("Name");
if(nameProperty == null)
return null;
using (var context = new MyContext())
{
object entity = context.Set(entityType).Find(id);
return nameProperty.GetValue(entity) as string;
}
}
The above works only if GetEntityByName method is defined in the same assembly and the same namespace as entity classes. Otherwise as parametr to GetType method you have to pass full type name.
Nameproperty defined?entityName, will it simply be the name of theclass("Car"), or the fullTypename? Also, are all the requested Entities in the same namespace?