Add or remove column mapping at runtime for linq2db

965 Views Asked by At

I have a scenario where if certain features are deployed then a number of columns will be there in some tables otherwise won't so the mapping of Entities and Columns is not static. I need to add/remove the mapping at runtime. Is there any way?

1

There are 1 best solutions below

2
On BEST ANSWER

Prepare a new MappingSchema and pass to DataConnection constructor.

Consider you have the following class:

[Table]
class SampleClass
{
    [Column] public int Id    { get; set; }
    [Column] public int Value { get; set; }
}

To remove column from full object materialization, do the following:

var ms = new MappingSchema();

ms.GetFluentMappingBuilder()
    .Entity<SampleClass>().Property(e => e.Value).IsNotColumn();

// cache somewhere this schema

using (var db = new DataConnection(ms))
{
    var result = db.GetTable<SampleClass>().ToArray();
}

Remember, better to cache this new MappingSchema and reuse. Otherwise you will never have cache hit and you'll lose performance.