views:

1286

answers:

1

Hi,

I'm trying to write the following short line of code in a more generic way.

What I want to achieve is a simple count of records, that have changed or were created since a certain date.

    public int GetChanges(DateTime LastActivityDate)
    {
        KHS.Innopas.Web.Library.DataModels.Documentation.DocumentationEntities ctx = 
            new KHS.Innopas.Web.Library.DataModels.Documentation.DocumentationEntities();

        return ctx.Images.Count(row => row.CreatedAt > LastActivityDate);
    }

I want to change the sample above to a more generic function like

    public int GetChanges(MetaTable table, string columnName, DateTime LastActivityDate)
    {
        return table.Count(row => row.columnName > LastActivityDate);
    }

What I tried until now is

    public int GetChanges(MetaTable table, string columnName, DateTime lastActivityDate)
    {
                    // query = {Table(LanguageText)}
        var query = table.GetQuery();

        MetaColumn dateColumn;
        table.TryGetColumn(columnName,out dateColumn);

        if (dateColumn == null)
            return new string[] {};

        var entityParam = Expression.Parameter(table.EntityType, "row");

        var property = Expression.Property(entityParam, dateColumn.Name);

        var columnLambda = Expression.Lambda(property, entityParam);

        var constant = Expression.Constant(lastActivityDate);

        var GreaterThanCall = Expression.GreaterThan(columnLambda.Body, constant);

        var whereLambda = Expression.Lambda(GreaterThanCall, entityParam);


        var whereCall = Expression.Call(
           typeof(Queryable),
           "Count",
           new Type[] { query.ElementType },
           query.Expression,
           whereLambda);

        var result = query.Provider.CreateQuery(whereCall);

        return result ;
    }

The problem is now, that 'whereCall' is incorrect and throws a (german) error. Any ideas, how it has to look like?

Thanks for your help. Sebastian

Further info: This is the german error:

Abfrageausdrücke für 'LINQ to Entities' können nur aus Instanzen konstruiert werden, die die IQueryable-Schnittstelle implementieren. Parametername: expression

+1  A: 
midas06