gpt4 book ai didi

c# - 使用 Entity Framework、LINQ 进行预加载

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:05 25 4
gpt4 key购买 nike

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

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}
}

我只想根据 B 类(其中 A1 = 4)选择 C ​​类的 C1 属性。我尝试使用:

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),因为结果中不包含任何嵌套实体。

预加载用于解决 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

关于c# - 使用 Entity Framework、LINQ 进行预加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31830823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com