API模型中的空引用

时间:2019-07-15 17:31:52

标签: c# entity-framework-core

我正在尝试通过使用代码优先方法生成数据库的标准Rest API来学习Entity Framework Core。我在从当前GET端点返回的JSON中获取空值,并且可以用一只手来弄清楚我哪里出错了。当前,这些控制器是由Entity Framework Core生成的默认脚手架控制器。

问题是我GET安装时返回的JSON是:

{
    "installId": 1,
    "aadUser": "Mr. Doe",
    "progress": 0,
    "practice": null  //Shouldn't this reference a specific Practice?
}

这是一对一的关系。

模型类:

public class Install
{
    public long InstallId { get; set; }
    public string AADUser { get; set; }
    public int Progress { get; set; }

    public Practice Practice { get; set; }
}

public class Practice
{
    public long PracticeId { get; set; }
    public string Name { get; set; }
    public string Specialty { get; set; }

    public long InstallId { get; set; }
    public Install Install { get; set; }

    public ICollection<User> Users { get; set; }
    public ICollection<User_Access> Users_Access { get; set; }
    public ICollection<Billing> Billing { get; set; }
    public ICollection<Location> Locations { get; set; }
    public ICollection<Resource> Resources { get; set; }
}

上下文片段:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
        //Install
        modelBuilder.Entity<Install>(entity =>
        {
            entity.HasKey(e => e.InstallId);

            entity.HasOne(d => d.Practice)
                .WithOne(p => p.Install)
                .OnDelete(DeleteBehavior.Cascade);

            //Seed Database
            entity.HasData(new Install()
                {
                    InstallId = 1,
                    AADUser = "Mr. Doe",
                    Progress = 0
                 });
        });

        //Practice
        modelBuilder.Entity<Practice>(entity =>
        {
            entity.HasKey(e => e.PracticeId);

            entity.HasOne(d => d.Install)
                .WithOne(p => p.Practice)
                .OnDelete(DeleteBehavior.ClientSetNull);

            //Seed Database
            entity.HasData(new Practice()
            {
                PracticeId = 1,
                Name = "Doe & Associates",
                Specialty = "Family Medicine",
                InstallId = 1
            });
        });
}

控制器:

[HttpGet]
public async Task<ActionResult<IEnumerable<Install>>> GetInstalls()
{
    return await _context.Installs.ToListAsync();
}

1 个答案:

答案 0 :(得分:1)

EF Core不会自动包含相关对象。

您需要在查询中包含它

await _context.Installs.Include(install => install.Practice).ToListAsync();

更多信息链接: https://docs.microsoft.com/en-us/ef/core/querying/related-data