0

I am currently programming game which is using C# connected with Entity Framework.

I have a lot of relationships with tables which are main models used in game. Because of that i have to use a lot of navigational properties of those models.

When i create my viewModel i have code similar to this :

        Avatar = new ImageViewModel(company.Entity.ImgUrl);
        CountryName = company.Region.Country.Entity.Name;
        RegionName = company.Region.Name;
        Name = company.Entity.Name;
        Money = MoneyViewModel.GetMoney(company.Entity.Wallet);
        OwnerName = company.Owner.Name;
        OwnerID = company.OwnerID;

Naturally it ends up firing multiple queries when i want to access navigational proprties.

I addressed this problem by using Include in my Controller before passing model to the view model constructor. this is heavily consuming my time because in the end i need to recursively check which navigational properties are needed in my view models and include them manualy in first query.

My question is : Is this code design apropriate? If not then what is correct approach to this kind of problem?

Personally i feel that it will be cumbersome in long term.

Shoter
  • 976
  • 11
  • 23

2 Answers2

1

As long as you're using eager loading, you need to manually include all the needed nested navigation properties. But that costs the better preformance.

So, if you have repetitive queries in diffrenet places in your code, which include the same navigational properties, you can facilitate your job by extracting them in extension method. Check the answer in Entity Framework - Is there a way to automatically eager-load child entities without Include()?, which shows an appropriate example how to do that.

Community
  • 1
  • 1
Tanya Petkova
  • 155
  • 1
  • 1
  • 7
1

As long as you have eager loading selected You have to manually include what you need. This is the price you pay for performance.

I would approach this in a different way. I would create Views and stored procedure that would give me the desired data fields, and then use Automapper to transfer the values directly into DTO classes.

This is usually what I do, and it pays off. I get the performance, but also keep everything very simple and maintainable.

user853710
  • 1,715
  • 1
  • 13
  • 27