简体   繁体   English

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

[英]Entity Framework 4: How to extend an entity?

I have imported database tables to .edmx file and among the others I have a Customer entity like: 我已将数据库表导入.edmx文件,其他我有一个Customer实体,如:

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} . 现在我想允许用户编辑所选客户,我需要显示每个客户的订单数量,因此在显示版本表单时,我需要动态地向该实体添加一个字段 - 字段CustOrderCount将评估一个sql语句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: 有没有办法以某种方式扩展实体,以便EF选择订单计数而无需手动执行如下自定义选择:

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

In the project where your edmx file live, create a new partial class : 在您的EDMX文件居住的项目,创建一个新的partial class

public partial class Customer {}

You can then add your own properties/methods to the EF entity: 然后,您可以将自己的属性/方法添加到EF实体:

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

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. 为此,您必须在显示时进行投影,使用@Jason显示的自定义数据检索。

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操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM