使用Dapper点网映射域实体的私有属性 [英] Mapping private attributes of domain entities with Dapper dot net

查看:69
本文介绍了使用Dapper点网映射域实体的私有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的大多数项目中,我都使用nHibernate + Fluent映射,最近我开始与Dapper一起玩,看看是否可以将读取操作移至它.

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.

我遵循DDD方法,因此我的域实体没有任何公共设置者.例如:

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;} }
}

使用Fluent nHibernate,我可以显示要映射的成员:

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");

是否可以使用Dapper映射域实体?如果是这样,怎么办?

推荐答案

一个选项是创建一组单独的持久性类,以与Dapper一起使用.例如:UserRecord和CarRecord.记录类将与db表匹配,并将被封装在持久性模块中.Dapper查询将针对此类运行,然后您可以拥有一个单独的持久性工厂,该工厂将组装域实体并将其返回给客户端.

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.

小例子:

        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.

这篇关于使用Dapper点网映射域实体的私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆