Search code examples
c#ormmappingfluentlinq2db

linq2db how to iterate over Properties in Fluent Mapping?


I am using the ORM linq2db.
We have the need to set the column names at runtime. That's why I can't use the attributes in the POCO-Class and instead use the Fluent Mapping Api (which is not documented as far as I know).

Because the column names will be determined at runtime I want to iterate over all properties in my Entities and set the Columnname.

In EF Core 3.x this would look like something like this:

foreach (var property in modelBuilder.Model.GetEntityTypes()
        .SelectMany(t => t.GetProperties()))
{
   property.SetColumnname(columnNameDict[property.Name]);
}

Is there a possibility to iterate over all the Properties in my Model, like in EF Core?

In linq2db to set the properties of a Property I have to use code like this:

builder
    .Entity<Addresses>()
    .HasTableName("ADDRESSES")
    .Property(x => x.Company) // This is the Membergetter, which i can't use in a foreach afaik.
    .HasColumnName("TEXT1")

To Access the Property ID I have to use "x => x.ID"(Expression<Func<Addresses, object>> memberGetter), but when I Iterate over the Properties, I don't know how to select the correct Property (PropertyMappingBuilder) without using this Expression (memberGetter) or how to set this Expression in a foreach. Is there a string overload like this .Property("Company")? I coudn't find any.

I tried it with reflection, but the Expression part didn't work ;):

foreach (var property in typeof(Addresses).GetProperties())
{
    var fieldInfo = adressenInfo.GetFieldByUser(property.Name);
    adressenBuilder.Property(a => property.GetValue(a)) // this line doesn't work
                   .HasColumnName(fieldInfo.LogicalName)
                   .HasDbType(fieldInfo.DataBaseType);    
}

Any Ideas are welcome! Thanks :)


Solution

  • You need to generate proper LambdaExpression manually for Parameter() method.

    var param = Expression.Parameter(typeof(Addresses));
    adressenBuilder.Property(Expression.Lambda<Func<Addresses, object>>(
        Expression.Convert(Expression.Field(param, fieldInfo), typeof(object)),
        param))...