1

I need to check entity in geenric service if it is Entity type, I should add dynamic expression where .Where("IsDeleted==false");

var result = _entityRepo.All();

var isEntityType = typeof(Entity).IsAssignableFrom(typeof(T));
if (isEntityType)
{
    var expression = CreateExpression("IsDeleted", true);
    var casted = (Expression<Func<T, bool>>)expression;
    result = result.Where(casted);
}
return result;

_entityRepo is GenericRepository<T>

public static Expression CreateExpression(string propertyName, bool valueToCompare)
{
    // get the type of entity
    var entityType = typeof(Entity);
    // get the type of the value object
    var entityProperty = entityType.GetProperty(propertyName);

    // Expression: "entity"
    var parameter = Expression.Parameter(entityType, "entity");

    // check if the property type is a value type
    // only value types work
    // Expression: entity.Property == value
    return Expression.Equal(
        Expression.Property(parameter, entityProperty),
        Expression.Constant(valueToCompare)
    );
}

off course I get error on cast:

Unable to cast object of type 'System.Linq.Expressions.LogicalBinaryExpression' to type 'System.Linq.Expressions.Expression1[System.Func2[MadCloud.Domain.Auditing.AuditCategory,System.Boolean]]'.

poke
  • 369,085
  • 72
  • 557
  • 602
Mediator
  • 14,951
  • 35
  • 113
  • 191
  • 3
    You don't really need nor want expression magic for this. Just use an `IDeletableEntity` interface that declares the `IsDeleted` property. – CodeCaster Sep 09 '15 at 10:16
  • Could you please tell more? – Mediator Sep 09 '15 at 10:35
  • Maybe you should make it less generic and define a BaseEntity that supports the IsDeleted option. – MrFox Sep 09 '15 at 11:00
  • Probably your problem goes deeper: What is about NavigationProperties which should be checked for IsDeleted. If that is the case, then possible duplicate: http://stackoverflow.com/q/12760933/3411327 – user3411327 Sep 09 '15 at 13:58

1 Answers1

1

Assuming IsDeleted is part of the Entity type, just cast to it:

IEnumerable<T> result = _entityRepo.All();
bool isEntityType = typeof(Entity).IsAssignableFrom(typeof(T));
if (isEntityType)
{
    result = result.Where(x => ((Entity)(object)x).IsDeleted == true);
}
return result;

After all, you know that Entity is assignable from T, so you can make the cast. Note that you need to cast it first to object in order to disable the compiler’s type checks at compile time. See also this answer.

Community
  • 1
  • 1
poke
  • 369,085
  • 72
  • 557
  • 602