存储库; POCO / Linq-to-Sql 实体类之间的映射
我正在使用 Sql Express 制作我的第一个数据库程序。目前,我正在使用 Linq-to-Sql 进行数据访问,并且我的存储库类返回“实体”类型对象。意义;我扩展了 dbml 实体类以用作我的业务对象类。现在我想让它更加分离;并拥有 POCO 业务对象。
这就是我想知道可能存在哪些不同的解决方案的地方。在我看来,我需要在存储库中手动将属性逐个属性、每个实体类映射到域类。到目前为止,我有大约 20 个表,总共几百列。现在..我只想验证这是否是您仍在使用的常见/典型方法?如果有替代方案而不引入过度复杂性,那会是什么?
I'm making my first database program, with Sql Express. Currently I'm using Linq-to-Sql for data access, and my repository classes return "entity" type objects. Meaning; I extend the dbml entity classes to use as my business object classes. Now I want to make this more separated; and have POCO bussiness objects.
This is where I wonder about what different solutions may exist. It looks to me like I need to manually map property-by-property, each entity class into domain class, in the repositories. I have so far about 20 tables with total few hundred columns. Now.. I just want to verify if this is a common/typical approach that you still use? And if there are alternatives without introducing excessive complexity, what would that be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在手动创建映射之前,请查看 AutoMapper
Before creating your mappings manually, have a look at AutoMapper
AutoMapper 是一个很好的工具,可以用来执行类到类的转换。然而,我正在考虑结合 Linq2Sql 和 AutoMapper 的 DAL,并且我在想为什么不直接使用 Fluent NHibernate?它非常容易设置,适用于几乎任何数据库,包括 SqlExpress,并且有一个可以无缝集成的 Linq 提供程序。所有这些都是免费的开源代码,并且非常常用,因此有充足的文档和支持。
如果您想继续使用 Linq2Sql 但拥有功能更齐全的域模型,您可以考虑从 DTO 派生域模型。这将允许您在域中拥有业务逻辑,并将属性传递给 DTO。但是,请了解 Linq2SQL 对象将无法直接转换为域对象;您需要在域中使用一个构造函数,该构造函数接受 DTO 并将信息复制到域中(至少需要 DTO 到域的单向映射)。然而,域可以被视为 DTO(因为类始终是其父类),因此不需要反向转换;只需将域类传递到需要 DTO 的存储库即可。
AutoMapper is a good tool to use to perform class-to-class conversions. However, I'm thinking of a DAL that combines Linq2Sql and AutoMapper, and I'm thinking why not just go with Fluent NHibernate? It's very easy to set up, works on just about any database including SqlExpress, and there is a Linq provider that integrates pretty seamlessly. All of this is free open-source code, and very commonly-used so there's ample documentation and support.
If you want to stay with Linq2Sql but have a more full-featured domain model, you could consider deriving your domain model from the DTOs. That would allow you to have the business logic in the domain, with the properties passed up to the DTO. However, understand that the Linq2SQL objects will not be able to be directly cast to domain objects; you'll need a constructor in the domain that takes a DTO and copies the info into the domain (requiring at least a one-way mapping of DTO to domain). However, the domain can be treated like a DTO (because a class is always its parent) so the reverse conversion isn't necessary; just hand the domain class to the repository where it would expect the DTO.