Entity Framework - Download only selected properties

I have no experience in this EF and therefore do not know the relevance of the issue.

Suppose I have tables called Student (StudentId, Name, Username, Address, DOB, DeptId, NavigationProp1Id ....) and in the Department table (Deptd, DeptName., NavigationProPid). Thus, if the structure of the table is as follows, when I use "contex.Studnets", I can get all the properties with it, including navigation properties, and if table 2 has other navigation properties, it can also be loaded. I'm right?

If so, does this cause any performance issues? Can I load only selected properties from Entity, for example, only UserName, Address from Student?

+6
source share
2 answers

No navigation properties are loaded immediately. They are loaded either explicitly if you use the Include method or lazily the first time you access them (this is also the reason why you see them in the debugger = access through the debugger caused lazy loading).

You can only load selected properties - this is called a projection. The limitation is that you cannot load a student object with a subset of properties. You need either a new class or an anonymous type:

 var query = context.Students.Select(x => new { x.UserName, x.Address }); 
+20
source

When using Entity Framework (EF), the best solution is to query the EF context using LINQ ( http://msdn.microsoft.com/en-us/library/bb308959.aspx ). LINQ can be used for relationship queries, so in your scenario your code will look like this:

 var joinedlist = context.Student.Join( // The table we wish to join to the Student table context.Department, // Item on student table we want to join from studentItem => studentItem.DeptId, // Item on department table we want to join to departmentItem => departmentItem.Deptd, // New object just holding the values we wish to retrieve from the joined tables (studentItem, departmentItem) => new { StudentId = studentItem.StudentId, StudentUsername = studentItem.Username, StudentAddress = studentItem.Address, DepartmentName = departmentItem.DeptName, Navigation = StudentItem.NavigationProp1Id } ); 

The above code will generate a list of queries for you, but with LINQ you can do a lot more. For example, selecting a subset of the data and filtering your results:

 var singleItem = joinedlist // Filter our joined list .Where(item => item.StudentId.Equals(1)) // Select only a subset of columns .Select(item => new {item.StudentUsername, item.StudentAddress}) // Return only a single item .FirstOrDefault(); 

As far as performance is concerned, I would suggest getting a profiler that can show you the SQL output of your LINQ statements in EF. It really helps when it comes to understanding lazy loading and where inappropriate .ToList () can return your entire DB!

+1
source

Source: https://habr.com/ru/post/1380525/


All Articles