实体框架4:如何扩展实体?
我已将数据库表导入到 .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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 edmx 文件所在的项目中,创建一个新的
partial
class
:然后您可以将自己的属性/方法添加到 EF 实体:
In the project where your edmx file live, create a new
partial
class
:You can then add your own properties/methods to the EF entity:
不会。实体仅从数据库中检索表本身中的字段。为此,您必须按照您所示进行投影,或者使用@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.
您可以在数据库中创建视图,将其映射为实体,并使用触发器来处理 CRUD 操作。
You can to create a view into your database, map it as your entity, and to use triggers to deal with CRUD operations.