Web api 实体框架将父元素嵌套在子元素中

Web api Entity-Framework nests parent inside child element

我在尝试将发票类型包含在其中时遇到问题。 Entity framework 在循环中填充嵌套实体,因此在映射后我最终得到嵌套在嵌套子实体中的父实体。

我配置的关系如下:

public partial class Invoice : IEntity<string>
{
    public string Id { get; set; }
    public string Number { get; set; }
    public ICollection<Type> Type { get; set; }
}

public partial class Type : 
{
    public string Type { get; set; }
    public string Number { get; set; }
    public Invoice Invoice { get; set; }
}

流利 api:

modelBuilder.Entity<Type>(entity =>
entity.HasOne(t => t.Invoice)
   .WithMany(f => f.Type)
   .HasForeignKey(f => f.Number)
   .HasPrincipalKey(f => f.Number);
}

结果我得到:

[
    {
        "Id": "1",
        "Number": "123",
        "Type": {
                  "Number": "123",
                  "TypeEnvoie": "PDF",
                  "Invoice": {
                            "Id": "1",
                            "Number": "123",
                            "Type": { ....
 

JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.

这是 ef 核心的常见错误。

我们通常在startup.csConfigureServices方法中添加如下配置来解决这个问题(3.0及以上):

 services.AddControllers().AddNewtonsoftJson(options =>
   options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);

注意前提是先在NuGet中下载Microsoft.AspNetCore.Mvc.NewtonsoftJsondll

结果如下: