0

I would like to store a "calculated field" in a Cosmos document.
For example, I would like to store CostGross to be used in reporting, but EFCore should be responsible for sending the value in inserts/updates:

    public class OrderItem
    {
        public decimal CostNet { get; set; }

        public decimal CostVat { get; set; }

        public decimal CostGross => CostNet + CostVat;
    }

expected document in Cosmos (trimmed for brevity):

{
    ...
    "CostNet": 1,
    "CostVat": 0.2,
    "CostGross": 1.2
    ...
}

actual document in Cosmos (trimmed for brevity):

{
    ...
    "CostNet": 1,
    "CostVat": 0.2
    ...
}

Is it possible to use EF to map a field so that the read only property appears in the document, meaning that the value doesn't have to be re-calculated by other clients doing a read operation?

Thanks

zXynK
  • 1,101
  • 16
  • 30

2 Answers2

0

Yes, you can save data in any object schema. Just populate OrderItem and save it.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Harshita Singh
  • 4,590
  • 1
  • 10
  • 13
0

In Ef core 3 this is possible but you need to tweak your model builder

See this GitHub issue https://github.com/dotnet/efcore/issues/18998#issuecomment-557702703

Relevant code

protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
 modelBuilder
     .Entity<User>()
     .Property(e => e.FullName)
     .UsePropertyAccessMode(PropertyAccessMode.Property); //need this line


 }

That should cause EF core 3.0 to store the computed property in the database since Ef would read the property instead of the backing fields directly

  • Hi, Thanks for your reply. Unfortunately this doesn't work without a setter either: `System.InvalidOperationException: 'The property 'OrderItem.CostGross' does not have a setter. Either make the property writable or use a different 'PropertyAccessMode'.'` – zXynK Apr 06 '21 at 08:44
  • @zXynK If you want to hack around, my next thought would be to add a setter that does nothing, just an empty set – RubberChickenLeader Apr 06 '21 at 13:31
  • that's my approach at the moment but I was hoping to avoid that – zXynK Apr 07 '21 at 08:13