mardi 16 juin 2015

Loop through a list obtained by reflection --> objectType.GetProperty("listType").GetValue(object)

I have this interface

public interface IEFEntity
{
    object GetPKValue();
    bool PKHasNoValue();
}

I have a GenManager class with an unfinished method isInFKEntity:

public class GenManager<Entity, EntityKey> where Entity : class, IEFEntity
{
    public IQueryable<Entity> Items { get { return repo.Items; } }
    private IGenRepo<Entity, EntityKey> repo;

    public GenManager(IGenRepo<Entity, EntityKey> repo) { this.repo = repo; }

    public Entity find(EntityKey pk) { return repo.find(pk); }
    public RepoResult delete(EntityKey pk) { return repo.delete(pk); }
    public RepoResult create(Entity item) { return repo.create(item); }
    public RepoResult update(Entity item) { return repo.update(item); }

    public bool isInFKEntity<FKEntity, FKEntityKey>(EntityKey pk, FKEntityKey fk) where FKEntity : class, IEFEntity
    {
        Entity dbEntry = find(pk);
        if (dbEntry == null) throw new InvalidOperationException(RepoMessages.dbEntryIsNull(new List<object> { pk }));

        var FKEntityList = typeof(Entity).GetProperty(typeof(FKEntity).Name).GetValue(dbEntry);
        //Gives a list back at runtime
        //But I can't use a foreach loop on it while coding
        //Also intellisense only shows the 4 methods of object

        var FKEntityListWithCast = typeof(Entity).GetProperty(typeof(FKEntity).Name).GetValue(dbEntry) as List<FKEntity>;
        //Gives a NULL value back at runtime
        //But I CAN use a foreach loop while coding
        //Intellisense has al the linq methods available!

        return false;
    }

}

Instead of returning false ofcourse I want to use:

return FKEntityListWithCast.Any(item => item.GetPKValue().ToString() == fk.ToString());

But as commented in the code the FKEntityListWithCast has no value(NULL) at runtime.

And using:

return FKEntityList.Any(item => item.GetPKValue().ToString() == fk.ToString());

is simple not possible because using the Any() method on FKEntityList doesn't compile.

If I try to use FKEntityList in a foreach I get the message: foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'.

Anyone know how to make this work??





Aucun commentaire:

Enregistrer un commentaire