Answer the question
In order to leave comments, you need to log in
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
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)
}
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 questionAsk a Question
731 491 924 answers to any question