net_prog
net_prog

Reputation: 10251

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:

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()
}  

Upvotes: 1

Views: 841

Answers (3)

Rubens Farias
Rubens Farias

Reputation: 57956

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

Upvotes: 0

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

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.

Upvotes: 1

Jason Evans
Jason Evans

Reputation: 29186

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(){}
}

Upvotes: 2

Related Questions