实体框架4:如何扩展实体?

发布于 2024-12-10 10:44:35 字数 536 浏览 0 评论 0原文

我已将数据库表导入到 .edmx 文件中,其中我有一个 Customer 实体,例如:

CustID
CustName
CustAddress

现在我想允许用户编辑选定的客户,我需要显示每个客户的订单数量,因此在显示版本表单时,我需要向该实体动态添加一个字段 - 字段 CustOrderCount ,它将评估 SQL 语句 SELECT COUNT(*) FROM订单 WHERE 客户 ID = {id}

有没有办法以某种方式扩展实体,以便 EF 选择订单计数,而无需手动执行如下所示的自定义选择:

.Select(c => new CustomerExtended 
{ 
    CustID = c.CustID, 
    ... 
    CustOrderCount = db.Orders.Where(o => o.OrderCustID = c.CustID).Count()
}  

I have imported database tables to .edmx file and among the others I have a Customer entity like:

CustID
CustName
CustAddress

Now I want to allow the user to edit the selected customers and I need to show the number of orders each customer has, so upon showing the edition form I need to add a field dynamically to this entity - field CustOrderCount which will evaluate a sql statement SELECT COUNT(*) FROM Orders WHERE CustomerID = {id}.

Is there a way to extend the entity somehow so the order count is selected by EF without manually doing a custom select like this:

.Select(c => new CustomerExtended 
{ 
    CustID = c.CustID, 
    ... 
    CustOrderCount = db.Orders.Where(o => o.OrderCustID = c.CustID).Count()
}  

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

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

发布评论

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

评论(3

电影里的梦 2024-12-17 10:44:35

在 edmx 文件所在的项目中,创建一个新的 partial class

public partial class Customer {}

然后您可以将自己的属性/方法添加到 EF 实体:

public partial class Customer {
   public int GetSomething(){}
}

In the project where your edmx file live, create a new partial class:

public partial class Customer {}

You can then add your own properties/methods to the EF entity:

public partial class Customer {
   public int GetSomething(){}
}
人心善变 2024-12-17 10:44:35

不会。实体仅从数据库中检索表本身中的字段。为此,您必须按照您所示进行投影,或者使用@Jason 所示的自定义数据检索。

在这种情况下,投影到自定义视图模型是正确的解决方案,因为您想要显示一些不属于实体的附加数据。

No. Entity retrieves from database only fields which are in the table itself. For this purpose you must either do a projection as you showed, use custom data retrieval as @Jason showed.

The projection to custom view model is correct solution in this case because you want to show some additional data which are not part of your entity.

几味少女 2024-12-17 10:44:35

您可以在数据库中创建视图,将其映射为实体,并使用触发器来处理 CRUD 操作。

You can to create a view into your database, map it as your entity, and to use triggers to deal with CRUD operations.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文