E
E
eugene732017-02-21 17:52:56
C++ / C#
eugene73, 2017-02-21 17:52:56

How to create a calculated field in a Code First Entity Framework 6 model?

Good afternoon.
I am creating a Code First data model in Entity Framework 6. There was a need to create a computable property for an entity. For example, the quantity for a document is the sum of the quantities for all its lines, so it is wrong to store such a field in a table. In SQL I would write:
select *
, coalesce((select sum(r.Quantity) from DocumentRows r where r.document_id=d.id), 0) as Quantity from
Documents d
where
just such a query so that the Quantity property of the Document entity is, but the field in the table is not?
Entities are described something like this:
public partial class Document
{
public Guid id {get; private set; }
public virtual ICollection Rows {get; private set;}
...
}
public partial class DocumentRow
{
public Guid id {get; private set;}
public virtual Document Document {get; set;}
public decimal Quantity {get; set;}
...
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2017-02-21
@eugene73

Create a partial class for the Document entity named Document.MyExtensionBlaBla.cs ; add a new property TotalQuantity to it and define the logic for its calculation:

public partial class Document
{
     public decimal TotalQuantity => Rows.Sum(x => x.Quantity)
}

Subsequently, this property can be accessed from the Document instance. For example, like this:
Where id is the input parameter of the searched document, which is its unique identifier.

M
MrDywar Pichugin, 2017-02-21
@Dywar

I had a similar question and I found this Computed Columns , it only works with the same table where the entity is located.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question