Skip to content

Multiple entity mappings

MoonStorm edited this page Jun 3, 2024 · 3 revisions

This is a unique concept that helps in data migration accross multiple types of databases, partial selects and updates, and so much more. Every entity has a default mapping attached, which informs FastCrud about how to construct the SQL queries. This default mapping can be set or queried via OrmConfiguration.SetDefaultEntityMapping and OrmConfiguration.GetDefaultEntityMapping.

Alternatively you can have other mappings tweaked for the same entities, which can be passed to any of the CRUD methods. These mappings should be built once and reused, and you can do so by either cloning an existing instance or by creating one from scratch.

    var partialUpdateMapping = OrmConfiguration
        .GetDefaultEntityMapping<Employee>()
        .Clone() // clone it if you don't want to modify the default
        .UpdatePropertiesExcluding(prop=>prop.IsExcludedFromUpdates=true, nameof(Employee.LastName));

    databaseConnection.Update(
        new Employee { 
            Id=id, 
            LastName="The only field that is going to get updated"
        }, statement => statement.WithEntityMappingOverride(customMapping));

In the previous example, only the LastName field will be updated.

You can also remove entire property mappings, which allows you to work with a subset of your pre-generated entity for any db operations, useful for large denormalized tables:

   var partialSetMapping = OrmConfiguration
      .GetDefaultEntityMapping<CompanyInformation>()
      .Clone() // clone it if you don't want to modify the default
      .RemoveAllPropertiesExcluding(
                            nameof(CompanyInformation.Id),
                            nameof(CompanyInformation.Email),
                            nameof(CompanyInformation.Phone),
                            nameof(CompanyInformation.Name));

You can also create a mapping that uses a different dialect, useful for migrating data from one database type to another.

    var destinationMapping = OrmConfiguration
    	.GetDefaultEntityMapping<CompanyInformation>
    	.Clone() // clone it if you don't want to modify the default
    	.SetDialect(SqlDialect.SqLite);

You can then pass this mapping to any of the CRUD methods.