public class A
{
public string Name { get; set }
public ICollection<B> b { get; set; }
}
public class B
{
public string Name { get; set }
public ICollection<A> a { get; set; }
}
從 .NET 5.0 開始,我們不需要創建連接類,我的資料已成功插入到表 A 和 B 以及連接表(其中有 A 和 B 的 PK)中。
但是當我嘗試檢索資料時:
DBConext.A.b.count
我得到 0。我仔細檢查了我的資料庫,發現資料在那里,表 A、B 和連接表 AB,我知道這可能是一個小問題,有人請幫助我
uj5u.com熱心網友回復:
您需要使用Include 方法指定要包含在查詢結果中的相關資料。但是您不能簡單地使用DBContext.A.Include(a => a.b).b.count來獲取計數。由于您的兩個表包含多對多關系。
如果您想獲得特定的 A 類(通過特定的 id 或名稱...)相關的 B 類計數,您可以使用:
public class TestController : ControllerBase
{
private readonly Dotnetcore5_0Context _context;
public TestController(Dotnetcore5_0Context context)
{
_context = context;
}
[HttpGet]
public void Get()
{
//get the count of B class if A's Name equals to aa
var data = _context.A.Include(a => a.b)
.Where(a=>a.Name=="aa").ToList()
.Select(a => a.b.Count()).ToList();
}
}
如果要獲取所有A類的相關B類計數,可以使用:
public class TestController : ControllerBase
{
private readonly Dotnetcore5_0Context _context;
public TestController(Dotnetcore5_0Context context)
{
_context = context;
}
[HttpGet]
public void Get()
{
var data = _context.A.Include(a => a.b).ToList()
.Select(a => a.b.Count()).ToList();
}
}
uj5u.com熱心網友回復:
除了 Rena 的回答之外,如果您使用惰性代理,您可以簡化很多事情。
在 DbContext 中,添加以下內容:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLazyLoadingProxies();
...
}
當您獲取一個/兩個物體的關系時,這可能很有用。如果要加載多個物件的關系,最好使用Include,因為資料將從一個 DB 請求加載,而不是數百個。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/349451.html
標籤:C# asp.net核心 实体框架核心 多对多 ef-core-5.0
