Entity Framework - Run function after properties are populated

asp.net-mvc, c#, entity-framework, lazy-loading, properties

Solution

there is no onload event where you could execute your code.

However you could make the GatherRate a function. (with a possible check to only compute the rate if a private variable is set to null

[NotMapped]
private int? _GaterRate;

public int GaterRate() {
    if (!_GaterRate.HasValue)
        GaterRate = GetAllResourceGatherers();//this would have to return the GatherRate of course;

    return _GaterRate.Value;
 }

you could even make it in a special get function this way to be computed when GaterRate is null (called the first time 1 would presume)

Problem

Is there a way to populate properties after Entity Framework has loaded the entity? For example - I have an object that has a couple of non-mapped properties that I need to populate after Entity Framework has loaded all of the other properties. I tried to put the logic to populate the properties into the constructor but it is running before any of the other properties are populated so they all read as `null`. ``` public class Planet { public Planet() { //this does not work because the Structures //and Ships properties return null GetAllResourceGatherers(); } public int Id { get; set; } public ICollection<Structure> Structures { get; set; } public ICollection<Ship> Ships { get; set; } [NotMapped] public int GatherRate {get; private set;} public void GetAllResourceGatherers { var resourceGatherers = Ships.OfType<IResourceGatherer>().ToList(); resourceStorers.AddRange(Structures.OfType<IResourceStorer>().ToList()); foreach (var gatherer in resourceGatherers) { gatherRate += gatherer.GatherRate; } } } ``` To try to avoid the issue with navigation properties not loading in time I tried to force it by changing the `GetAllResourceGatherers()` method to: ``` public void GetAllResourceGatherers { using (var db = new DbContext()) { //This does not work because the 'Id' property comes back. //as 0 which is just default Structures = db.Structures.Where(x => x.ParentId == Id).ToList(); Ships = db.Ships.Where(x => x.ParentId == Id).ToList(); var resourceGatherers = Ships.OfType<IResourceGatherer>().ToList(); resourceStorers.AddRange(Structures.OfType<IResourceStorer>().ToList()); foreach (var gatherer in resourceGatherers) { gatherRate += gatherer.GatherRate; } } } ```

Original source