首页 > 解决方案 > 如何从 EF Core 导航属性转到嵌套的 Web API JSON 响应?

问题描述

我一直在尝试遵循一些基本的 .Net 核心教程,我想创建一个使用 EF Core 的 Asp.net Core Web API。

基本上 .Include() 似乎什么都不做,老实说,我什至不认为一开始这是一个必要的调用。

我有一个 API,它的 Goldfish 有想法,JSON 可以很好地返回到单独的对象,除了我的导航属性在金鱼上始终为 NULL:

[
{
    "id": 1,
    "name": "Bob",
    "isAlive": true,
    "food": 50,
    "ideas": null
},..

这是 Goldfish 类(它也不适用于 ICollection)

 public class Goldfish
{
    public long ID { get; set; }
    public string Name { get; set; }
    public bool IsAlive { get; set; }
    public long Food { get; set; }

    public IEnumerable<Idea> Ideas { get; set; }
}

这是 Idea 类(我出于绝望而使用外键属性使其工作,以前我有一个 GoldfishID 属性。

    public class Idea
{
    public long ID { get; set; }
    public string Title { get; set; }
    public string Gist { get; set; }
    public long GoldfishID { get; set; }

    [ForeignKey("GoldfishID")]
    public Goldfish Goldfish { get; set; }

}

我认为我的数据库没问题,因为我的 Idea 表上已经设置了外键:

ALTER TABLE [dbo].[Ideas]  WITH CHECK ADD  CONSTRAINT 
[FK_Ideas_Goldfish_GoldfishID] FOREIGN KEY([GoldfishID])
REFERENCES [dbo].[Goldfish] ([ID])
ON DELETE CASCADE
GO

但是当我访问我的控制器方法时:

        [HttpGet]
    public IEnumerable<Goldfish> GetAll()
    {
        var stuff = _context.Goldfish.Include(i => i.Ideas);

        return stuff.ToList();
       // return _context.Goldfish.ToList();
    }

多亏了我在全世界最喜欢的工具,我知道运行的 SQL 没有连接,也没有任何获得想法的尝试——我的金鱼脑死了 :(

    SELECT [g].[ID], [g].[Food], [g].[IsAlive], [g].[Name]
FROM [Goldfish] AS [g]

请让我知道我哪里出错了……我的返回类型不包括我想要的结构类型吗?我会说我没有在 OnModelCreating 中明确设置所需的一对多,因为教程没有这样做,这是我的整个上下文:

    public class GoldfishContext : DbContext
{
    public GoldfishContext(DbContextOptions<GoldfishContext> options)
        : base(options)
    {
    }

    public DbSet<Goldfish> Goldfish { get; set; }
    public DbSet<Idea> Ideas { get; set; }

    //Interrupt the standard configuration of table names, the tutorial has this and it's nice to keep ffr
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Goldfish>().ToTable("Goldfish");


    }
}

我应该提一下!我在我的 DBInitialise 中添加了这些想法,它们肯定存在于数据库中:

            var pondideas = new Idea[]
        {
            new Idea {Title="Bobs idea", Gist = "Give bob food", GoldfishID=1},
            new Idea {Title="Bobs second idea", Gist = "Give bob more food", GoldfishID=1},
            new Idea {Title="Nice idea", Gist = "Feed everyone", GoldfishID=1},
            new Idea {Title="terrible idea", Gist = "Feed nobody", GoldfishID=1}
        };

标签: .netjsonasp.net-coreentity-framework-coreasp.net-core-webapi

解决方案


已经指出了正确的方向(感谢 Shyju),我想明确地提出解决方案:

.Include() 的正确包是 Microsoft.EntityFrameworkCore

您需要添加的内容: using Microsoft.EntityFrameworkCore;

代码将以错误的版本(.Net 框架)运行,但 include 不会执行任何操作。

一旦您添加了正确的库,并且如果您的模型像我的一样链接,您的 API 将超时,除非您将以下 JsonOptions 添加到您的 Startup 中以防止循环引用混乱:

            services.AddMvc()
        .AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

推荐阅读