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!

2
  • 1
    What do you mean by it didn't work? Are you getting any error? How are you using the extension method? Commented Nov 25, 2019 at 11:09
  • There are no errors. After my extension method execution fluentMappingBuilder had no any properties, but ID. Commented Nov 25, 2019 at 11:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This is more or less the answer. This will need to be done in the for loop for each property
Thanks, but I have error with cast Int32 to object here var lambda = Expression.Lambda<Func<T, object>>(property, parameter);
@canton7 cannot convert from 'System.Linq.Expressions.UnaryExpression' to 'System.Linq.Expressions.ParameterExpression' on this var lambda = Expression.Lambda<Func<T, object>>(property, cast); cast is red underlined
@canton7 Thank you, very much! I was stuck on this stupid thing))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.