0

I have the following class

public class InvestorsLottery : Lottery 
{
    [Column(TypeName = "decimal(14, 2)")]
    public decimal Investment { get; set; }
    [Required]
    public int Percentage { get; set; }
    [Required]
    [Column(TypeName = "decimal(30, 18)")]
    public decimal InvestmentEth 
    { 
        get { return _investmentEth; } 
        set { 
             _investmentEth = Investment / EthPrice; 
             value = _investmentEth
        } 
    }
    private decimal _investmentEth;
}

with the following fluent api

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<InvestorsLottery>()
           .Property(p => p.InvestmentEth)
           .HasField("_investmentEth")
           .UsePropertyAccessMode(PropertyAccessMode.Field);
}

but the value of InvestmentEth stays zero - how can I change this?

Noah Bergh
  • 493
  • 4
  • 14
  • 1
    Your setter for `InvestmentEth` is wrong. It should have `value` in its body. [guide](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties) – Wootiae Sep 26 '21 at 17:17
  • started to mess around thanks but still it doesnt save the value – Noah Bergh Sep 26 '21 at 17:25
  • does adding the backingfield attribute help? [BackingField(nameof(_investmentEth))] to the InvestmentEth property – SmithMart Sep 26 '21 at 17:31
  • see: https://learn.microsoft.com/en-us/ef/core/modeling/backing-field?tabs=data-annotations – SmithMart Sep 26 '21 at 17:32
  • Additionally, the docs seem to point to it assigning directly to the backing field which is likely also what you want as you'd probably not want to do maths on the property as it comes out of the DB – SmithMart Sep 26 '21 at 17:33
  • It may be a better option to turn this into a [computed column](https://learn.microsoft.com/en-us/ef/core/modeling/generated-properties?tabs=data-annotations#computed-columns) in the database. That solves all kinds of possible redundancy conflicts. – Gert Arnold Sep 26 '21 at 18:18
  • Why do you want to go through all these steps? Like Gert mentioned, add it as a computed column OR just add another property that is marked as [NotMapped]. All entity classes are marked partial. You can add as many members as you want without affecting the migration. – Mayur Ekbote Sep 26 '21 at 18:26
  • Could you give me an example of a computed column with sql query? @MayurEkbote – Noah Bergh Sep 26 '21 at 20:27

0 Answers0