传递表达式而不是 lambda

Pass Expression instead lambda

全部! 默认情况下,我将尝试为添加映射数据库列编写扩展。我使用 linq2db

这是我的方法

    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));
        }
    }

它没有用...但是如果我这样写 - 一切正常

       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);

我认为我的问题是属性表达式错误。你能帮帮我吗?

谢谢!

x => x.IDx => Expression.Property(item, "ID") 不同。

你想做的大概是:

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);
}

也就是我们要自己构建整个LambdaExpression