c# - Eager Loading with Entity Framework, LINQ -
i working on asp.net mvc project. using ef code-first approach. have 3 classes, are:
public class { public int aid {get;set;} public string a1 {get;set} public string a2 {get;set} public virtual list<b> bs {get;set;} } public class b { public int bid {get;set;} public string b1 {get;set} public string b2 {get;set} public aid {get;set} public virtual a {get;set} public virtual list<c> cs {get;set;} } public class c { public int cid {get;set;} public string c1 {get;set} public string c2 {get;set} public bid {get;set} public virtual b b {get;set} }
i want select c1 properties of class c based on class b a1 = 4 . tried using:
var result = db.c.select(x=>x.c1).include(x=>b).where(x=>x.a.equals(4))
i confused , don't know how execute linq query. not sure whether continue using eager loading or fall on else.
please can guru me out please?
try this:
var result = db.c .where(c => c.b.a.a1 == 4) .select(c => c.c1) .tolist()
you don't have use eager loading (include
) here because none of nested entities contained in result.
eager loading used workaround select n + 1 problem. problem arises when retrieve parent entity , want iterate through children. results in n + 1 requests made database.
here code samples illustrate:
without eager loading
var carlist = db.cars.tolist(); //this create 1 request database retrieve cars foreach(var car in carlist) { foreach(var wheel in car.wheels) //this line create request database retrieve wheels specific car } console.write("car = {0}, wheel = {1}", car, wheel); } } //total requests: 1 car list + n requests retrieve wheels n - total number of cars
with eager loading
var carlist = db.cars.include(x => x.wheels).tolist(); //this create 1 request database retrieve cars information wheels foreach(var car in carlist) { foreach(var wheel in car.wheels) //this line won't create request database because data has been loaded using eager loading } console.write("car = {0}, wheel = {1}", car, wheel); } } //total requests: 1 car list wheel information
Comments
Post a Comment