簡體   English   中英

使用 LINQ 方法語法返回父實體及其子實體

[英]Return a parent entity together with its child entities using LINQ method syntax

NET Core Web API 項目,並且有一個 Get 操作方法,它在傳入 id 時返回一個實體(Keyfield)。 我想修改此方法,使其返回相同的實體,但現在與其子實體(參考字段)一起返回。 如何在此 Get 方法中使用 LINQ 方法語法在對數據庫的同一調用中獲取此信息?

我的獲取方法:

[HttpGet("{id}")]
public async Task<ActionResult<KeyField>> GetKeyField(int id)
{
   var keyField = await _context.KeyFields.FindAsync(id);

   if (keyField == null)
   {
            return NotFound();
   }

   return keyField;
}

我的兩個班級:

public class KeyField
{
    public int KeyFieldId { get; set; }
    public string KeyName { get; set; }
    public string ShortDesc { get; set; }

    public List<ReferenceField> ReferenceFields { get; set; }

子實體:

public class ReferenceField
{
    public int ReferenceFieldId { get; set; }
    public int KeyFieldId { get; set; }
    public virtual KeyField KeyField { get; set; }

    public string FieldName { get; set; }
    public string Instructions { get; set; }
}

使用Eager 加載

[HttpGet("{id}")]
public async Task<ActionResult<KeyField>> GetKeyField(int id)
{
   var keyField = await _context.Set<KeyField>()
                         .Where(x => x.KeyFieldId == id)
                         .Include(x => x.ReferenceFields)
                         .FirstOrDefaultAsync();

   if (keyField == null)
   {
            return NotFound();
   }

   return keyField;
}

或者啟用延遲加載作為另一個選項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM