, , ? , .
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)
{
}
}
}
Name:
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;
}
}
:
string name = GetEntityByName<Car>(id);
, , , :
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;
}
}
, GetEntityByName , . GetType .