我的问题与这个问题类似:仓储模式与领域模型和实体框架之间的映射。
我在这里读了很多关于以下内容的文章:
将ORM直接映射到领域模型
将ORM映射到数据模型,然后将数据模型映射到领域模型(反之亦然)
我理解两种方法的优点和局限性。我也理解哪种方法在什么场景下更受欢迎。
网上有很多示例演示如何执行选项1。但是,我找不到任何示例代码来显示如何执行选项2。我阅读了关于选项二的问题,例如本帖子第一行引用的问题,即问题涉及选项二,但答案涉及选项一,并且有评论指出选项二可能更合适。
因此,我的问题具体涉及从映射和验证角度执行选项一的方式:
映射
我相信我可以在将领域模型映射到数据模型时执行此操作:
public PersonDomain GetById(Guid id)
{
return AutoMapper.Mapper.Map<PersonDomain>(Session.Get<PersonData>(id));
}
我相信在将数据模型映射到存储库中的领域模型时(为了保护不变量),我已经做到了这一点:
protected PersonDomain ToPersonDomain(PersonData personData)
{
return new PersonDomain(personData.ID, personData.Name, personData.DateOfBirth);
}
验证
我想在PersonDomain类中实现此操作:
public class PersonDomain
{
public Guid ID{ get; private set; }
public DateTime DateOfBirth { get; private set; }
public string Name { get; private set; }
public PersonDomain(Guid id, DateTime dateOfBirth, string name)
{
if (id == Guid.Empty())
throw new ArgumentException("Guid cannot be empty");
if (name =="")
throw new ArgumentException("Name cannot be empty");
ID = id;
Name = NAME;
DateOfBirth = dateOfBirth;
}
}
然而,我找到的每个示例都告诉我不要将验证放在构造函数中。我想到的一个办法是避免原始类型偏执,具体如下:
public class PersonDomain
{
public ID ID{ get; private set; }
public DateOfBirth DateOfBirth { get; private set; }
public Name Name { get; private set; }
public PersonDomain(ID id, DateOfBirth dateOfBirth, Name name)
{
if (id == null)
throw new ArgumentNullException("ID cannot be null");
if (name ==null)
throw new ArgumentNullException("Name cannot be null");
ID = id;
Name = name;
DateOfBirth = dateOfBirth;
}
}
然而,在这种情况下,构造函数中仍然有验证。
问题:
我的两个问题是:
1. 我是否正确理解了领域模型和数据模型之间的映射(以及反之),或者有更优雅的方法来处理这个问题(数据模型和领域模型之间的映射和反之)?
2. 在这种情况下,我应该在PersonDomain实体的构造函数中放置任何验证逻辑吗?
更新于27/02/18
此链接对我最有帮助:http://www.dataworks.ie/Blog/Item/entity_framework_5_with_automapper_and_repository_pattern
seal
类、必须将成员设置为virtual
、必须有零参数构造函数等。你知道还有其他的代码示例(可能不是完整的示例)吗?我不确定是否喜欢将状态作为领域对象的一个成员来单独保存。 - w0051977