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

asp.net-core c# entity-framework-core linq

Question

NET Core web API project, and there is one Get action method that returns an entity(Keyfield) when passing in an id. I would like to modify this method so that it returns the same entity but now together with its children entities(Referencefields). How can I get this within the same call to the database using LINQ method syntax inside this Get method?

My get method:

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

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

   return keyField;
}

My two classes:

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

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

The child entity:

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; }
}
1
0
2/26/2020 4:31:22 AM

Accepted Answer

Use Eager loading

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

Or enable Lazy Loading as another option.

0
2/26/2020 5:16:00 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow