直接从数据库加载演示模型

发布于 2024-09-18 19:10:29 字数 283 浏览 2 评论 0原文

我正在开发一个 2 层应用程序,其中 WinForms 客户端直接调用数据库。在其中一个场景中,我需要向用户显示客户实体列表。问题是 Customer 实体包含很多属性(有些属性相当重),而我只需要其中两个 - 名字和姓氏。因此,为了提高性能并使表示逻辑更清晰,我想创建某种仅具有所需属性的 CustomerSummaryViewModel 类,并使用 NHibernate 的投影功能来加载它。我在这里担心的是,在这种情况下,我的数据访问逻辑与表示耦合在一起,对我来说,这在概念上似乎是错误的。

您认为这样可以吗还是有更好的解决方案?

I'm working on a 2-tier application where WinForms client makes direct calls to the database. In one of the scenarios I need to display a list of Customer entities to a user. The problem is that Customer entity contains a lot of properties (some quite heavy) and I need only two of them - first and last names. So to improve performance and make presentation logic clearer I want to create some kind of a CustomerSummaryViewModel class with required properties only and use NHibernate's projections feature to load it. My concern here is that in this case my data access logic becomes coupled with presentation and to me it seems conceptually wrong.

Do you think this is ok or there are better solutions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苹果你个爱泡泡 2024-09-25 19:10:46

我认为您可以将 CustomerSummaryViewModel 视为报告(CustomerSummaryReport)。可以查询您的实体是否有这样的场景并将它们视为报告。大多数报告都更加复杂,使用多个实体和聚合查询。该报告非常简单,但您仍然可以像报告一样使用它。

您还提到性能很重要。这是使用单独的报告查询和 DTO 的另一个原因。客户实体听起来像是您使用的“主要”实体之一。由于延迟加载属性未初始化,因此需要花费大量时间从数据库中检索它们,这可能是优化客户实体本身的警告,而不是使用报告查询来检索有关它们的信息。只是一个警告,因为我见过需要这样做的案例。

顺便说一句,您可以考虑使用 linq 而不是投影,以获得更简单的语法,例如:

var reports = session.Linq<Customer>()
  .Where(condition)
  .Select(customer => new Report 
   { 
       FirstName = customer.FirstName, 
       LastName = customer.LastName 
   })
  .ToList();

I think you can consider the CustomerSummaryViewModel as report (CustomerSummaryReport). It is fine to query your entities for scenario's like this and treat them as reports. Most reports are more complex, using multiple entities and aggregate queries. This report is very simple, but you can still use it like a report.

You also mention that the performance is significant. That is another reason to use a separate reporting query and DTO. The customer entity sounds like one of the "main" entities you use. That it takes a significant amount of time to retrieve them from the database with lazy-loaded properties not initialized, can be a warning to optimize the customer entity itself, instead using reporting queries to retrieve information about them. Just a warning because I have seen cases where this was needed.

By the way, you can consider linq instead of projections for the easier syntax like:

var reports = session.Linq<Customer>()
  .Where(condition)
  .Select(customer => new Report 
   { 
       FirstName = customer.FirstName, 
       LastName = customer.LastName 
   })
  .ToList();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文