1

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!

RomanReaL D
  • 101
  • 5
  • 1
    What do you mean by `it didn't work`? Are you getting any error? How are you using the extension method? – Chetan Nov 25 '19 at 11:09
  • There are no errors. After my extension method execution fluentMappingBuilder had no any properties, but ID. – RomanReaL D Nov 25 '19 at 11:14

1 Answers1

2

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.

canton7
  • 37,633
  • 3
  • 64
  • 77
  • This is more or less the answer. This will need to be done in the `for` loop for each property – Nkosi Nov 25 '19 at 11:55
  • Thanks, but I have error with cast Int32 to object here var lambda = Expression.Lambda>(property, parameter); – RomanReaL D Nov 25 '19 at 12:01
  • @canton7 cannot convert from 'System.Linq.Expressions.UnaryExpression' to 'System.Linq.Expressions.ParameterExpression' on this var lambda = Expression.Lambda>(property, cast); cast is red underlined – RomanReaL D Nov 25 '19 at 12:09
  • 1
    @canton7 Thank you, very much! I was stuck on this stupid thing)) – RomanReaL D Nov 25 '19 at 12:23