假设我想创建一个博客应用程序,其中包含这两个与 EF Code First 或 NHibernate 一起使用并从存储库层返回的简单持久性类:
public class PostPersistence
{
public int Id { get; set; }
public string Text { get; set; }
public IList<LikePersistence> Likes { get; set; }
}
public class LikePersistence
{
public int Id { get; set; }
//... some other properties
}
我想不出一种将持久性模型映射到域模型的干净方法。我希望我的Post
域模型界面看起来像这样:
public interface IPost
{
int Id { get; }
string Text { get; set; }
public IEnumerable<ILike> Likes { get; }
void Like();
}
现在下面的实现会是什么样子?也许是这样的:
public class Post : IPost
{
private readonly PostPersistence _postPersistence;
private readonly INotificationService _notificationService;
public int Id
{
get { return _postPersistence.Id }
}
public string Text
{
get { return _postPersistence.Text; }
set { _postPersistence.Text = value; }
}
public IEnumerable<ILike> Likes
{
//this seems really out of place
return _postPersistence.Likes.Select(likePersistence => new Like(likePersistence ));
}
public Post(PostPersistence postPersistence, INotificationService notificationService)
{
_postPersistence = postPersistence;
_notificationService = notificationService;
}
public void Like()
{
_postPersistence.Likes.Add(new LikePersistence());
_notificationService.NotifyPostLiked(Id);
}
}
我花了一些时间阅读有关 DDD 的内容,但大多数示例都是理论上的或在域层中使用了相同的 ORM 类。我的解决方案似乎真的很丑,因为实际上域模型只是 ORM 类的包装器,它似乎不是以域为中心的方法。实现方式IEnumerable<ILike> Likes
也让我感到困扰,因为它不会从 LINQ to SQL 中受益。有哪些其他(具体的!)选项可以创建具有更透明持久性实现的域对象?