Entity Framework to create calculated (not mapped) fields?

c# entity-framework-6

Question

What should I do with Entity Framework to create calculated fields?

I'm using Entiry Framowork 6 with database first. Let say I have an entity with id, name, initialQuantity then en finalQuantity. finalQuantity is always 5% more than my initialQuantity. I don't want to persist this field in may database. I don't want to map it but I want the property in my entity.

How can I do that. Do I need to add this property to my edmx file? Do I need to create inheritance, partial class??

Also, after further reading it seems I cannot create an entity which is not mapped at all. Ok, so what is the alternative? And can I create an entity that is mapped with field that are not mapped?

1
0
5/30/2016 3:51:30 PM

Accepted Answer

Use [NotMapped] data annotation:

using System.ComponentModel.DataAnnotations;
public class MyEntity
{
    public MyEntity()
    { 
    }

    [Key]
    public int Id { get; set; }
    public decimal initialQuantity { get; set; }

    [NotMapped]
    public decimal finalQuantity => initialQuantity*1.05m;
}

If you don't want to map your entity, don't put it in your DbContext class.

0
5/30/2016 4:09:10 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow