Mapping private attributes of domain entities with Dapper dot net

c# dapper domain-driven-design fluent-nhibernate-mapping orm

Question

In most of my projects I use nHibernate + Fluent mapping and recently I've started to play around with Dapper to see if I can move read operations to it.

I follow DDD approach so my domain entities do not have any public setters. For example:

public class User
{
    private int _id;
    private string _name;
    private IList<Car> _carList;

    protected User(){} // Fluent Mapping

    public User(string id, string name)
    {
        // validation 
        // ...
        _id = id;
        _name = name;
    }

    public int Id{ get {return _id;} }
    public string Name { get {return _name;} }
    public IList<Car> CarList { get {return _carList;}}         
}

public class Car
{
    private int _id;
    private string _brand;

    protected Car(){} // Fluent Mapping

    public Car(string id, string brand)
    {
        // validation 
        // ...
        _id = id;
        _brand= brand;
    }

    public int Id{ get {return _id;} }
    public string Brand { get {return _brand;} }
}

With Fluent nHibernate I'm able to reveal members for mapping:

Id(Reveal.Member<User>("_id")).Column("id");
Map(Reveal.Member<User>("_name")).Column("name");

Is there a way to map my domain entities with Dapper? If so, how?

Accepted Answer

One option is to create a separate set of persistence classes to work with Dapper; for example: UserRecord and CarRecord. The record classes will match db table and will be encapsulate within persistence module. Dapper queries will run against this classes and then you can have a separate persistence factory which will assemble the domain entities and return them back to the client.

Small example:

        var carRecord = DbConnection.Query<CarRecord>("select * from cars where id = @id", new {id = 1});
        var carEntity = CarFactory.Build(carRecord);

This creates a nice separation and provides flexibility.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why