C#C
C#4y ago
Connor

❔ How to deal with property’s that need data from a database?

 public class Company
    {
        public float Rating { get; set; }
        public async Task<float> GetRating(IMongoService mongoService)
        {
            var locations = await mongoService.GetLocationsAsync(LocationIds);
          if(locations.Count == 0)
return 0;
           return locations.Average(location=> location.Rating)
       
        }

public List<string> LocationIds { get; set; } = new List<string>();
    }

I have a Blazor page where I want to display a Company’s rating which is the average of its location ratings. The problem is, I only store the locationIds on the company, not all the data. The best, botched solution I’ve come up with is doing company.Rating = company.GetRating() on initialization (I need the mongo service from the Blazor page to even get it); I can’t remove the Rating property because you can put as async method in html.

I feel like a better solution might lie in Lazy initialization or something. I really don’t know though, hence why I’m here.

I’m also currently “cluttering” the db of Companies with a Rating property that is always 0 (I get it on demand)
Was this page helpful?