Linq to Sql、存储库和 Asp.Net MVC ViewData:如何删除冗余?
Linq to SQL 创建可 IQueryable 且充满关系的对象。
Html Helpers 需要特定的界面对象,例如 IEnumerable
。
我认为可能会发生什么:
- 重用从 Linq 到 SQL 的对象而不带所有包袱,即从 Linq 到 SQL 对象返回 Pocos,而不需要额外的域模型类?
- 提取可以轻松转换为(或本身)Html 辅助对象(例如 SelectListItem 枚举)的对象?
有没有办法在不破坏关注点分离的情况下做到这一点?一些巧妙的oop技巧来桥接需求?
例如,如果它位于存储库中,则 SelectListItem 将不存在。 select new
是一种从 Linq to SQL 中删除对象的好方法,但它仍然引用了一个不应该引用的类:
IEnumerable<SelectListItem> result = (from record in db.table
select new SelectListItem {
Selected = record.selected,
Text= record.Text,
Value= record.Value }
).AsEnumerable();
Linq to SQL creates objects which are IQueryable and full of relations.
Html Helpers require specific interface objects like IEnumerable<SelectListItem>
.
What I think could happen:
- Reuse the objects from Linq to SQL without all the baggage, i.e., return Pocos from the Linq to SQL objects without additional Domain Model classes?
- Extract objects that easily convert to (or are) Html helper objects like the SelectListItem enumeration?
Is there any way to do this without breaking separation of concerns? Some neat oop trick to bridge the needs?
For example, if this were within a repository, the SelectListItem wouldn't be there. The select new
is a nice way to cut out an object from the Linq to SQL without the baggage but it's still referencing a class that shouldn't be referenced:
IEnumerable<SelectListItem> result = (from record in db.table
select new SelectListItem {
Selected = record.selected,
Text= record.Text,
Value= record.Value }
).AsEnumerable();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我见过IService接口和Service类的用户。基本上这是存储库和控制器之间的步骤。
优点:
缺点:
我确信还有更多,但这是我见过和使用过的。
I have seen the user of an IService interface and Service class. Basically it's the step between the repository and the controller.
Pros:
Cons:
I'm sure there are more, but that's something I've seen and used.
在此特定示例中,您可以在分部类定义中创建 ToSelectListItem() 方法或类似方法以删除重复项。或者也许扩展方法会更好地避免那里的一些耦合。
编辑:我通常将 JSON Web 服务与 DTO 一起使用。我可能有 ProductDto,它是我的 Product L2SQL 实体的扁平 JSON 友好表示。然后我只需在查询中调用 select ProductDto.FromProduct(product) 即可。现在重复已经很少了。
In this specific example, you can create a ToSelectListItem() method or similar in your partial class definition to remove duplication. Or maybe an extension method would be better to avoid some coupling there.
Edit: I generally use JSON web services with DTOs. I might have ProductDto that is my flattened JSON-friendly representation of my Product L2SQL entity. Then I just have to call select ProductDto.FromProduct(product) in my query. The duplication is now minimal.