Custom Property Type Mapping

Linq2Db allows you to use custom property types (e.g. Money, Percent) in your entity models while mapping them to standard database types.

Code samples

To map a custom class to a specific database type, use either of the following

mappingSchema.SetDataType(typeof(Money), DataType.Money);
// OR
mappingSchema.SetDataType(typeof(Percent), new SqlDataType(DataType.Decimal, typeof(decimal), 9, 6));

This ensures that table creation and value casting in queries use the correct underlying SQL type.

If you need to use custom types in query parameters or materialise them from database values, defined conversion expressions so Linq2Db knows how to handle them:

mappingSchema.SetConvertExpression<Money, decimal>(money => money.Value); // Used for writing this value to SQL when set as a property of an in-memory object
mappingSchema.SetConvertExpression<decimal, Money>(@decimal => new Money(@decimal)); // Used for reading this value from SQL to in-memory
mappingSchema.SetConvertExpression<Money, DataParameter>(money => new DataParameter { Value = money.Value, DataType = DataType.Money }); // Used for setting query parameters

Further reading