【发布时间】:2012-12-06 03:42:48
【问题描述】:
假设我想创建一个博客应用程序,其中包含这两个与 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 中受益。还有哪些其他(具体的!)选项可以创建具有更透明持久性实现的域对象?
【问题讨论】:
-
这是什么语言?用您正在使用的编程语言标记您的问题真的很有帮助。您应该将 C# 和 .Net 添加到问题的标签中。
-
我已经添加了这些标签,但我的问题更独立于平台。任何用 OO 语言写的答案都会让我满意。
-
不幸的是,EF 并不理想,因为如果您希望 EF 管理您的实体,您要么必须执行您所描述的操作,要么必须使用自动属性“公开”您的类并拥有默认的无参数构造函数
标签: c# .net architecture domain-driven-design persistence