在我的大部分项目中,我使用 nHibernate + Fluent 映射,最近我开始尝试使用 Dapper 看看是否可以将读取操作移至它。
我遵循 DDD 方法,因此我的域实体没有任何公共(public) setter 。例如:
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,我可以显示映射成员:
Id(Reveal.Member<User>("_id")).Column("id");
Map(Reveal.Member<User>("_name")).Column("name");
有没有办法用 Dapper 映射我的域实体?如果是,怎么做?
最佳答案
一个选择是创建一组单独的持久性类来与 Dapper 一起工作;例如:UserRecord 和 CarRecord。记录类将匹配数据库表并将封装在持久性模块中。 Dapper 查询将针对此类运行,然后您可以拥有一个单独的持久性工厂,该工厂将组装域实体并将它们返回给客户端。
小例子:
var carRecord = DbConnection.Query<CarRecord>("select * from cars where id = @id", new {id = 1});
var carEntity = CarFactory.Build(carRecord);
这创造了一个很好的分离并提供了灵 active 。
关于c# - 使用 Dapper 点网映射域实体的私有(private)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15299946/