RomanReaL D
RomanReaL D

Reputation: 101

Pass Expression instead lambda

all! I'll try to write extention for add mapping db column by defaults. I using linq2db

this is my method

    public static void EntityWithDefaults<T>(this FluentMappingBuilder fluentMappingBuilder) {
        fluentMappingBuilder.Entity<T>().HasTableName(typeof(T).Name);
        var item = Expression.Parameter(typeof(T), typeof(T).Name);
        foreach (var prop in typeof(T).GetProperties()) {
            if (prop.Name == "ID")
                fluentMappingBuilder.Entity<T>().Property(x => Expression.Property(item, prop.Name)).IsIdentity().IsPrimaryKey();
            else
                fluentMappingBuilder.Entity<T>().Property(x => Expression.Property(item, prop.Name));
        }
    }

it didn't work... but if I write like this - all is ok

       fluentMappingBuilder.Entity<AppLogLong>()
       .HasTableName("AppLog")
       .Property(x => x.ID).IsPrimaryKey().IsIdentity()
       .Property(x => x.ActionDate)
       .Property(x => x.ActionId)
       .Property(x => x.EmployeeId)
       .Property(x => x.RequestType);

I think my problem is wrong expressions for properties. Could you help me, plz?

Thanks!

Upvotes: 1

Views: 244

Answers (1)

canton7
canton7

Reputation: 42225

x => x.ID is not the same as x => Expression.Property(item, "ID").

What you want to do is probably:

foreach (var prop in typeof(T).GetProperties()) {
    var parameter = Expression.Parameter(typeof(T), "x");
    var property = Expression.Property(parameter, prop);
    var cast = Expression.Convert(property, typeof(object));
    var lambda = Expression.Lambda<Func<T, object>>(cast, parameter);
    if (prop.Name == "ID")
        fluentMappingBuilder.Entity<T>().Property(lambda).IsIdentity().IsPrimaryKey();
    else
        fluentMappingBuilder.Entity<T>().Property(lambda);
}

That is, we have to construct the entire LambdaExpression ourselves.

Upvotes: 2

Related Questions