Include or Not Include Related Models in a Query in EF Core

03.05.2021 10:42
#EF-CORE #NET-CORE #İNCLUDE-PROPERTY

Include or Not Include Related Models in a Query in EF Core

I will explain the process of including or not including related models to the query, which I learned as a result of the need in a project I developed with .Net Core.

There may be nested dependent models in a query you make. If you do not need these related models during your query, you will be pulling data unnecessarily. This will cause the project to slow down.

If you have done the relational structure properly, by default the relational models will return empty. If you want to include your relational models in the query, the method you use is the include method. To give an example of its usage, it will be as follows.


Model Structure Used

public class Products

{

    public int ProductID { get; set; }

    public string ProductName { get; set; }

    public int ProductOwnerID { get; set; }

    public  User ProductOwner { get; set; }

}

    public class User

    {

        public int UserID { get; set; }

        public string UserFirstName { get; set; }

        public string UserLastName { get; set; }

        public ICollection<Product> Products { get; set; }

    }

EF Core Include Method

context.Products.Include(x=>x.ProductOwner).OrderBy(x => x.ProductID);

If you write the Include method, it will include the information of the project owner in your current query.

If you do not want to include related models in your query, simply delete the include method.

Note: In some cases, even if we delete include, associated models continue to come. In this case, if we include the AsNoTracking () method in our query, the problem disappears.