Dynamic table selection using entity structure

I have a property name for various objects such as a car, person, etc. Depending on Idwhat I want to get a name. But I would like to make it executed in one method, which takes the name entityName and gives a result depending on this. Something like that:

public string GetEntityByName(int id,string entityName)
    {
        using (var context = new MyContext())
        {
            return context[entityName].Find(id).Name;
        }
    }
+4
source share
2 answers

All your entities must extend the base class or implement the interface that defines the property Name.

public interface INamed {
     string Name { get; set; }
}

public class Car : INamed {
     public int Id { get; set; }
     public string Name { get; set; }
}

I don't know if DbContextindexed properties are supported , but if so, you can do something like this:

INamed namedEntity = context[entityName].Find(id) as INamed;
if(namedEntity != null)
     return namedEntity.Name;
else
     return string.Empty;

, INamed, :

return ((INamed)context[entityName].Find(id)).Name;

, , INamed

+2

, , ? , .

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
        }
    }
}

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 .

+1

All Articles