M
M
manst2014-10-31 23:56:44
Entity Framework
manst, 2014-10-31 23:56:44

How to optimize an Entity Framework query?

Good afternoon, I work with Entity Framework 6 and Asp.net MVC5, there are three entities: company, branch and user.

public class Company
    {
        public int Id { get; set; }
        public string Name { get; set; }

        
        public virtual ICollection<Branch> Branches { get; set; }

    }

    public class Branch
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int CompanyId { get; set; }
        
        public virtual Company Company { get; set; }
        public virtual ICollection<User> Users { get; set; }


    }

    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int BranchId { get; set; }
        
        public virtual Branch Branch { get; set; }
    }

In the controller code, I need to get the user entity with information on the branch to which it belongs and the company.
I do it like this:
var user = UserManage.Users.Include(b=>b.Branch.Company).FirstOrDefault(u=>u.Id == id);

Next, I pass the user to the view. And every time I access information about a branch or a company in a view, for example:
@Model.Branch.Company.Name
a query is made to the database.
How can the request be optimized so that the user receives all the information in the controller at once and when accessing from the view, no additional requests are formed?
And in general, is such a request rational:
var user = UserManage.Users.Include(b=>b.Branch.Company).FirstOrDefault(u=>u.Id == id);

since the sql code that forms EF is just scary :)
Does it make sense to break it into several simple queries, for example, getting the user first, then his branch, and then his company?
Maybe there is an easier way to get the data of his company from the user?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wkololo_4ever, 2014-11-01
@wkololo_4ever

"Next, I pass the user to the view. And every time I access information about the branch or company in the view, for example:
@Model.Branch.Company.Name
, a query is made to the database. "
var user = UserManage.Users.Include(b= >b.Branch.Company).FirstOrDefault(u=>u.Id == id).ToList();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question