Reputation: 959
I have no hands on experience it EF and hence dont know the relevence of the question.
Suppose I have tables named Student (StudentId, Name, Username, Address, DOB, DeptId, NavigationProp1Id.... ) and in Department table (Deptd, DeptName., NavigationProPid). So if a table structure follows like this, when I use 'contex.Studnets ' I can get all prpoerties along with it including navigation properties and if table 2 has other navigation properties it can also be loaded. Am I correct?
If so whether it cause any performance issue? Can I load only selected properties from Entity like only UserName, Address from Student entity?
Upvotes: 6
Views: 12737
Reputation: 99
When using Entity Framework (EF) your best solution is to query the EF context using LINQ (http://msdn.microsoft.com/en-us/library/bb308959.aspx). LINQ can be used to query across relationships, so in your scenario your code would look like the following:
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 for you a queryable list, but you can do many more things with LINQ. For example selecting a subset of 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();
Regarding performance - I would suggest getting hold of a profiler which can show you the SQL output of your LINQ statements on EF. This really helps when it comes to understanding lazy loading and where a misplaced .ToList() may be returning your entire DB!
Upvotes: 1
Reputation: 364409
No navigation properties are not loaded immediately. They are loaded either explicitly if you use Include
method or lazily when you access them for the first time (that is also reason why you see them in debugger = access through debugger caused lazy loading).
You can load only selected properties - it is called projection. The limitation is that you cannot load Student entity with subset of properties. You need either new class or anonymous type:
var query = context.Students.Select(x => new
{
x.UserName,
x.Address
});
Upvotes: 21