C# update parent object when new child is added

c# entity-framework-6 visual-studio

Question

Although not my situation, I created this example to figure out how to resolve my issue. The models I have using Entity Framework are as follows:

namespace ClassTesting.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Player
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Player()
        {
            this.Deposit_Transactions = new HashSet<Deposit_Transactions>();
        }

        public long id { get; set; }
        public string player_name { get; set; }
        public decimal player_balance { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Deposit_Transactions> Deposit_Transactions { get; set; }
    }
}

namespace ClassTesting.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Deposit_Transactions
    {
        public long id { get; set; }
        public System.DateTime transaction_date { get; set; }
        public decimal transaction_amount { get; set; }
        public long fk_player_id { get; set; }

        public virtual Player Player { get; set; }
    }
}

A Player may thus have several Deposit Transactions.

What I want to do is update the Player's player balance property each time a new Deposit Transaction is issued. I can accomplish it, but my workaround requires retrieving the player record and doing the change after the payment has been made, which is rather cumbersome. What I want to know is what is the "best practice" method for doing this?

1
2
9/11/2018 12:31:33 PM

Accepted Answer

Considering thatplayer_balance consists of a compilation of that player'sDeposit_Transactions , I highly urge you to deleteplayer_balance retrieved from the relevant database table. Your model is now denormalized, which causes it to store the same conceptual data several times and cause it to lose sync.

This is a more significant issue that is not limited to your EF model and raises the possibility of faults throughout the whole system.

The column may be changed or removed from the table.player_balance into a calculated, read-only property while keeping its convenience.

public partial class Player
{
    public decimal player_balance => 
        Deposit_Transactions.Sum(transaction => transaction.transaction_amount);
} 
2
9/16/2018 7:21:39 AM


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