Execute lambda expressions from an "unknown" type


In a development that I am doing, I create a type of object from one of my classes that are stored in my library in the following way:

  var type = GetTypeFromAssembly(typeName, fullNameSpaceType);
        var instanceOfMyType = Activator.CreateInstance(type);
        ReadObject(instanceOfMyType.GetType().GetProperties(), instanceOfMyType, fullNameSpaceType);
        return instanceOfMyType;

Then using Entity Framework I need to obtain by ID the values belonging to that object by instantiating in the aforementioned way and to be dynamic I do it in the following way:

var parameter = Expression.Parameter(typeof(TObject));

        var condition =
            Expression.Lambda<Func<TObject, bool>>(
                    Expression.Property(parameter, theEntity.GetType().GetProperty("Id").Name),
                    Expression.Constant(id, typeof(TKey))
                    ), parameter

        var theObject = _unitOfWork.Set<TObject>().Where(condition).FirstOrDefault();

The issue is that my TObject is of the type of the object that I dynamically instantiated when trying to execute the expression does not execute the process correctly and sends the following error:


Instance property 'Id' has not been defined for type 'System.Object'

Which is true since I'm sending the type object and I need to send the type of the instance of my object made in reflection, that is:

var theObject = _catalogService.CreateObjectInstance(catalog, "Cms.Spv.Entities");
        _catalogService.GetObjectById<Guid, theObject>(id, theObject);

Any way to do this?

asked by user18452 13.10.2016 в 21:23

1 answer


I do not know the first part of the code, but if you're already talking about Entity Framework, an easy way to get an element based on its context from your Id is like this.

var MiObjeto = context.Set<T>().Find(PK);

Where T is the entity data type and PK is the Id.

On the other hand make expressions from an unknown type until now I could not: (

But I could solve it using a generic class

public abstract class MiClaseGenerica<T> : IMiClaseGenerica<T> where T : class
    public T ObtenerPorId(long PK)
        return context.Set<T>().Find(PK);

public interface IMiClaseGenerica<T> : IDisposable where T : class
    T ObtenerPorId(long PK);

Another way in which I think this can be solved is to use a common interface for the ethos as a type.

return _unitOfWork.Set<IComun>().Where(x=> x.PropiedadComun==id).FirstOrDefault();


answered by 09.12.2016 в 02:43