Mappers - lobodava/artisan-orm GitHub Wiki
Mappers in Artisan.Orm are static classes decorated with MapperFor attribute.
Here is the mapper for User type:
[MapperFor(typeof(User)]
public static class UserMapper -- Name of a class does not matter
{Mapper methods work for two directions and each may have two static methods with reserved names:
- DataToObject direction — is to read data by SqlDataReader and return an object of
MapperFortype or anObjectRow:CreateObjectCreateObjectRow
- ObjectToData direction — is to create DataTable and populate it with an object data (for further passing it as a parameter to a stored procedure):
CreateDataTableCreateDataRow
CreateObject method reads data by SqlDataReader and returns an object of MapperFor type:
public static User CreateObject(SqlDataReader dr)
{
var i = 0;
return new User
{
Id = dr.GetInt32(i) ,
Login = dr.GetString(++i) ,
Name = dr.GetString(++i) ,
Email = dr.GetString(++i)
};
}The order and quantity of columns correspond to the select statement:
select Id, Login, Name, Email from dbo.Users;CreateObjectRow method reads data by SqlDataReader and returns an ObjectRow:
public static ObjectRow CreateObjectRow(SqlDataReader dr)
{
var i = 0;
return new ObjectRow(4)
{
/* 0 - Id = */ dr.GetInt32(i) ,
/* 1 - Login = */ dr.GetString(++i) ,
/* 2 - Name = */ dr.GetString(++i) ,
/* 3 - Email = */ dr.GetString(++i)
};
}CreateDataTable method creates DataTable which corresponds to a user-defined table type already existing in a database by quantity, type and order:
public static DataTable CreateDataTable()
{
return new DataTable("UserTableType")
.AddColumn< Int32 >( "Id" )
.AddColumn< String >( "Login" )
.AddColumn< String >( "Name" )
.AddColumn< String >( "Email" );
}The corresponding user-defined table type:
create type dbo.UserTableType as table
(
Id int not null primary key clustered,
[Login] varchar(20) not null ,
Name nvarchar(50) not null ,
Email varchar(50) not null
);CreateDataRow method creates Object[] where items correspond to columns in DataTable by quantity and order:
public static Object[] CreateDataRow(User obj)
{
if (obj.Id == 0)
obj.Id = Int32NegativeIdentity.Next;
return new object[]
{
obj.Id ,
obj.Login ,
obj.Name ,
obj.Email
};
}CreateDataRow is the right place to:
- assign Negative Identity for Id of new objects,
- propagate an object Id value to child items in its collections to make a link for a forign key,
- assign integer ParentId from Parent object,
- control and change data before it gets to a table valued parameter
See more examples of Mappers in Tests project:
- MapperFor(typeof(User) in Users
- MapperFor(typeof(Record) in Records
- MapperFor(typeof(Record) in GrandRecords
- MapperFor(typeof(RecordType) in GrandRecords
- MapperFor(typeof(GrandRecord) in GrandRecords
- MapperFor(typeof(ChildRecord) in GrandRecords
See also:
and: