使用 Entity Framework、LINQ 进行预加载

Eager Loading with Entity Framework, LINQ

我正在处理 ASP.NET MVC 项目。我正在使用 EF 代码优先方法。我有 3 个 classes,它们是:

public class A
{
    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 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}
}

我只想 select class C 基于 Class B 的 C1 属性,其中 A1 = 4 。 我尝试使用:

var result = db.C.select(x=>x.C1).Include(x=>B).where(x=>x.A.equals(4))

我很困惑,不知道如何执行linq查询。我也不确定是继续使用预加载还是退回到其他东西。

请各位大神帮帮我好吗?

试试这个:

var result = db.C
    .Where(c => c.B.A.A1 == 4)
    .Select(c => c.C1)
    .ToList()

您不必在此处使用预加载 (Include),因为结果中包含 none 个嵌套实体。

预先加载用于解决 SELECT N + 1 问题。当您检索父实体并想要遍历其子实体时,就会出现此问题。这导致对数据库发出 N + 1 个请求。

以下是用于说明的代码示例:

没有预先加载

var carList = db.Cars.ToList(); //this will create one request to the database to retrieve all cars

foreach(var car in carList)
{
    foreach(var wheel in car.Wheels) //this line will create another request to the database to retrieve wheels for specific car
    }
        Console.Write("Car = {0}, Wheel = {1}", car, wheel);
    }
}
//Total requests: 1 to get car list + N requests to retrieve wheels where N - total number of cars

预加载

var carList = db.Cars.Include(x => x.Wheels).ToList(); //this will create one request to the database to retrieve all cars together with information about wheels

foreach(var car in carList)
{
    foreach(var wheel in car.Wheels) //this line won't create extra request to the database because this data has been already loaded using eager loading
    }
        Console.Write("Car = {0}, Wheel = {1}", car, wheel);
    }
}
//Total requests: 1 to get car list with all wheel information

默认情况下,EF 使用延迟加载,这意味着您不会得到,除非您提出要求。使用 ToList() 或 ToArray() 让 EF 执行查询 sql 并将这些对象放入内存实体。 如果需要,您可以执行原始 sql 查询,例如 YourDbContext.SqlQuery<T>("select * from ...")