【问题标题】:Return a parent entity together with its child entities using LINQ method syntax使用 LINQ 方法语法返回父实体及其子实体
【发布时间】:2020-02-26 13:16:00
【问题描述】:

NET Core Web API 项目,并且有一个 Get 操作方法在传入 id 时返回一个实体(Keyfield)。我想修改此方法,使其返回相同的实体,但现在与其子实体(参考字段)一起返回。如何在此 Get 方法中使用 LINQ 方法语法在对数据库的同一调用中获取此信息?

我的get方法:

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

【问题讨论】:

    标签: c# linq asp.net-core entity-framework-core


    【解决方案1】:

    使用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;
    }
    

    或者启用Lazy Loading 作为另一个选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      相关资源
      最近更新 更多