C# update parent object when new child is added

c# entity-framework-6 visual-studio

Question

Not my scenario, but I have constructed this example to find out how to solve my problem. Using Entity Framework I have the following models;

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; }
    }
}

So a Player can have many Deposit_Transactions.

What I want to do is whenever a new Deposit_Transaction is posted, update the Player's player_balance attribute. I can do that, but my solution is really clunky and involves fetching the player record and doing the update after the deposit has been made. 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

Assuming that player_balance is some aggregation of that player's Deposit_Transactions, I strongly recommend that you remove player_balance from the corresponding database table. Currently, your model is denormalized, storing the same conceptual information in multiple locations and thereby allowing it to get out of sync.

This is a larger problem, not confined to your EF model, increasing the likelihood of bugs throughout the whole system.

You can remove the column from the table and change player_balance into a readonly, computed property retaining 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