dimanche 27 novembre 2016

Return the content of an EF model's DbSet based on type

I have an entity framework context with tables EntityTypeA, EntityTypeB ... EntityTypeZ. I would like to create a method which returns an IEnumerable of IEntityModel, or in other words the content of the tables listed above.

I currently have a switch which, based on the type provided as argument, returns the content of the corresponding table.

Please consider the following code that I'm trying to factorize:

IEnumerable<IEntityModel> GetAllEntitiesByType(Type entityType)
{
    NorthwindEntities en = new NorthwindEntities();
    switch (entityType.Name)
    {
        case "EntitiesTypeA":
            return en.EntitiesTypeA;
        // all types in between
        case "EntitiesTypeZ":
            return en.EntitiesTypeZ;
        default:
            throw new ArgumentException("Unknown model type: " + entityType);
    }
}

I would be surprised if there were no other more concise way to achieve the same result (by using reflection for instance) but I can't seem to find a useful example.

Any ideas please?





Aucun commentaire:

Enregistrer un commentaire