我一直在玩洋葱架构、DDD和规范模式。Entity Framework 有许多实现,其中域实体直接位于 context 的 DBSet<> 中。对我来说,这是不行的,至少因为多对多的关系。假设我们有下一个 dbo:
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public List<PostTag> PostTags { get; set; }
}
public class Tag
{
public string TagId { get; set; }
public string Name { get; set; }
public List<PostTag> PostTags { get; set; }
}
public class PostTag
{
public int PostId { get; set; }
public Post Post { get; set; }
public string TagId { get; set; }
public Tag Tag { get; set; }
}
问题是实体模型不应该知道任何关于它的信息,Post.PostTag
因为它是持久层实现的细节。例如,我可以将存储更改为 JSON 对象,并且不再需要中间表。因此,理想情况下,我的实体模型将如下所示:
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public List<Tag> Tags { get; set; }
}
public class Tag
{
public string TagId { get; set; }
public string Name { get; set; }
}
或者更糟糕的是,如果我们决定向 中添加一些新属性PostTag
,例如
public class PostTag
{
...
public bool IsActive { get; set; }
...
}
然后,它会影响Tag
在考虑这个带有实体模型的例子时。
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public List<Tag> Tags { get; set; }
}
public class Tag
{
public string TagId { get; set; }
public bool IsActive { get; set; } // this is added
public string Name { get; set; }
}
因此,我想要同时拥有实体和dbo模型。当我实现位于基础设施层的 PostRepository 时,我想公开IQueriable<Post> Query()
. 这是真正的问题开始了。问题的原因是作为存储库消费者的应用程序层只能在Post
实体内操作,而不能在实体内操作PostDbo
。它们可以不同。因此,我无法为该实体编写规范。因此,主要问题是如何实现可以公开这种Query()
方法的存储库模式,同时具有分离entity
和dbo
模型,而不会对查询的性能和优化产生严重影响。
或者,也许规范模式只是一个巨大的开销,它更有害而不是有用。原因是当您决定将实体框架更改为其他内容时,您应该为Expression<Func<TEntity>>
. 你怎么看?
也许我有什么问题,所以请纠正我。我将不胜感激合理的答案。
谢谢