-
Notifications
You must be signed in to change notification settings - Fork 24
Attribute Based Mapping
The alternative to the Convention Based Mapping that MicroLite offers is Attribute Based Mapping. Attribute Based Mapping is opt-in and achieved by applying attributes to the class and properties.
The Attribute Based Mapping is included in the main MicroLite assembly so you don't need to install an additional package. If you want to use Attribute Based Mapping, configure MicroLite to use the it in your application start-up:
// Do this before calling Configure.Fluently()...
Configure.Extensions().WithAttributeBasedMapping();
To specify the table name that the class is mapped to, apply the MicroLite.Mapping.TableAttribute
to the class.
[Table("Customers")]
public class Customer { }
If the database supports them, you an optionally specify a schema name.
[Table("Sales", "Customers")]
public class Customer { }
To specify the column name that a property is mapped to, apply the MicroLite.Mapping.ColumnAttribute
to the property. Properties must also have a public get
and set
to be used by MicroLite.
[Column("StatusId")] // Unless otherwise specified, the property can be inserted and updated.
public CustomerStatus Status { get; set; }
You can configure Insert or Update only properties.
[Column("Created", allowInsert: true, allowUpdate: false)]
public DateTime Created { get; set; }
[Column("Updated", allowInsert: false, allowUpdate: true)]
public DateTime Updated { get; set; }
Note: it is acceptable to have unmapped properties, if no ColumnAttribute
is applied to a property, MicroLite will ignore it when generating Insert, Update or Select statements.
To specify the property which maps to the identifier column in the table and the identifier strategy, apply the MicroLite.Mapping.IdentifierAttribute
to the property (this must be applied in addition to the ColumnAttribute).
[Column("CustomerId")]
[Identifier(IdentifierStrategy.DbGenerated)]
public int Id { get; set; }
If you use IdentifierStrategy.Sequence
, you also need to specify the sequence name:
[Column("CustomerId")]
[Identifier(IdentifierStrategy.Sequence, "CustomerIdSequence")]
public int Id { get; set; }