Skip to content

.NET Core example of using Dapper with the custom Xml and Json mappers

License

Notifications You must be signed in to change notification settings

kubagdynia/DapperMappers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

69 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DapperMappers

CI

An example of using Dapper with the custom Xml and Json mappers. Can be used to serialize and deserialize objects by Dapper.

Project structure

  • DapperMappers.Api - Sample REST API that uses serialization and deserialization to XML (uses the MS SQL Server Express database)
  • DapperMappers.Domain - Sample domain used by the REST API
  • DapperMappers.Domain.Tests - Domain tests using SQLite database
  • DbConnectionExtensions - DBConnection extension

How to use

  • Create a class that implements IXmlObjectType or IJsonObjectType interface
public class Book
{
	public long Id { get; set; }
	public string Title { get; set; }
	public BookDescription Description { get; set; }
}

public class BookDescription : IXmlObjectType
{
	public Learn Learn { get; set; }
	public string About { get; set; }
	public Features Features { get; set; }
}

public class Learn
{
	public List<string> Points { get; set; }
}

public class Features
{
	public List<string> Points { get; set; }
}
  • Register these new classes in Startup.cs
services.RegisterDapperCustomTypeHandlers(typeof(Book).Assembly);
  • Create a table in the database that contains a column of the XML type
CREATE TABLE [dbo].[Books](
	[Id] bigint IDENTITY(1,1) NOT NULL,
	[Title] nvarchar(200) NOT NULL,
	[Description] xml NULL
	CONSTRAINT [PK_Books] PRIMARY KEY CLUSTERED
	(
		[Id] ASC
	)
)
  • Use Dapper to save object data in the database
public async Task SaveBook(Book book)
{
	using (var conn = _connectionFactory.Connection())
	{
		await conn.ExecuteAsync(_@"INSERT INTO Books (Title, Description) VALUES (@Title, @Description)", book);
	}
}

How to Run test REST API

git clone https://github.com/kubagdynia/DapperMappers.git
{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=BookDB;Integrated Security=True;MultipleActiveResultSets=True;"
  }  
}
  • If you are running from IDE set the Startup Item to the DapperMappers.API project, not IIS Express
  • Running the API project from the command line
dotnet run --project .\DapperMappers\DapperMappers.Api\
  • Open the API documentation in your browser
https://localhost:5001/swagger

How to Test

Every commit or pull request is built and tested on the Continuous Integration system.

To test locally:

  • Download and install .NET 8.0 SDK
  • Clone or download source code
git clone https://github.com/kubagdynia/DapperMappers.git
  • Start tests from the command line
dotnet test ./DapperMappers/

Technologies

List of technologies, frameworks and libraries used for implementation:

License

This project is licensed under the MIT License.