Is Deferred Execution in Asp.net MVC View a very bad thing?

前端 未结 4 800
遥遥无期
遥遥无期 2020-11-29 08:54

Let\'s say i have the following model which is obtained via Entity Framework:

public class User{
 public string Name {get;set;}
 public int Id {get;set;}
}
<         


        
4条回答
  •  青春惊慌失措
    2020-11-29 09:32

    What you are doing it's OK for a "quick and dirty" solution. It's easy to do and it works, but it has some drawbacks if you want to do "proper" code:

    You are basically doing DB queries from the view, which is definitely not the place if you are doing a layered application. You should do the DB queries in the controllers for simple applications or in application services or even repositories for more structured and complex applications.

    Materializing the queries in the view has also problems in exception handling. The DB exceptions won't be thrown in the controller, so you can't handle them in the controller or on action filters.

    In terms of performance, I don't see how it can be different. What you should avoid though is to use lazy loading. If your User entity had a dependent entity or collection, EF would fire an extra query for each user, which would really impact the performance. Ideally you should disable lazy loading. If you follow the rule of sending all data to the view (no deferred queries), this also includes loading all dependent entities upfront.

提交回复
热议问题