C#
Nullが出ないようにするにはIncludeを使う
出典: Asp.NetCoreApiのModel外部参照でNullを防ぐならIncludeを使え! — Nullが出ないようにするにはIncludeを使う
// GET: api/Companies/5
[HttpGet("{id}/emp")]
public async Task<ActionResult<ICollection<Employee>>> GetCompanyEmp(int id)
{
//var company = await _context.Company.FindAsync(id);
//if (company == null)
//{
// return NotFound();
//}
//return company.Employees.ToList();
var company = await _context.Company.Include(com => com.Employees).FirstOrDefaultAsync(com => com.Id == id);
if (company == null)
{
return NotFound();
}
return company.Employees.ToList();
}
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
Source収録記事
この snippet は記事の「Nullが出ないようにするにはIncludeを使う」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
4 件namespace IncludeStudy.Models { public class Company {未収録
Asp.NetCoreApiのModel外部参照でNullが出る
#081405cf0fee
namespace IncludeStudy.Models { public class Employee {未収録
Asp.NetCoreApiのModel外部参照でNullが出る
#77f64dbdbb38
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks;未収録
Asp.NetCoreApiのModel外部参照でNullが出る
#87439b15ae9e
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers();未収録
JsonExceptionが出た場合は下記をする。
#7cf68e77babf
