Entity Framework Core:包含破坏Http响应

3
我遇到了一个问题,正在设置Entity Framework Core和Asp .NET Core中的简单多对多关系,这让我很疯狂。每当我尝试使用Includes()方法返回相关集合时,我的HTTP响应就会出错。能否有人帮我解决一下?
以下是Product和Category类之间的简单关系示例:
public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public ICollection<ProductCategory> ProductCategories { get; set; }
}

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public ICollection<ProductCategory> ProductCategories { get; set; }
}

public class ProductCategory
{
    public int ProductId { get; set; }
    public int CategoryId { get; set; }
    public Product Product { get; set; }
    public Category Category { get; set; }
}

同时还有Entity Framework DbContext:

public class ProductDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<ProductCategory> ProductCategories { get; set; }

    public ProductDbContext(DbContextOptions<ProductDbContext> options) : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ProductCategory>().HasKey(s => new { s.ProductId, s.CategoryId });

        base.OnModelCreating(modelBuilder);
    }
}

这里有一个控制器,带有一个Set方法(快速填充数据的方式),以及一个Get方法来获取结果:

public class ProductController : Controller
{
    ProductDbContext _context;

    public ProductController(ProductDbContext context)
    {
        _context = context;
    }

    public IActionResult Set()
    {
        _context.Products.AddRange(
            new Product
            {
                Name = "TestProduct1"
            },
            new Product
            {
                Name = "TestProduct2"
            }
            );

        _context.Categories.AddRange(
            new Category
            {
                Name = "TestCategory1"
            },
            new Category
            {
                Name = "TestCategory2"
            }
            );

        _context.SaveChanges();

        _context.ProductCategories.AddRange(
            new ProductCategory
            {
                ProductId = 1,
                CategoryId = 1
            },
            new ProductCategory
            {
                ProductId = 2,
                CategoryId = 1
            },
            new ProductCategory
            {
                ProductId = 2,
                CategoryId = 2
            }
            );

        _context.SaveChanges();

        return Ok();
    }

    public IActionResult Get()
    {
        var products = _context.Products
            //.Include(p => p.ProductCategories)
            .ToList();
        return Ok(products);
    }
}

为了进行测试,我首先通过Postman访问Set方法(http://localhost:54551/product/set)。之后,访问Get方法(http://localhost:54551/product/get)会返回以下内容:

[
    {
        "productId": 1,
        "name": "TestProduct1",
        "productCategories": null
    },
    {
        "productId": 2,
        "name": "TestProduct2",
        "productCategories": null
    }
]

然而,取消注释Get方法中的Includes调用会导致以下结果:
无法获取任何响应。
There was an error connecting to http://localhost:54551/product/get.
Why this might have happened:
The server couldn't send a response:
Ensure that the backend is working properly
Self-signed SSL certificates are being blocked:
Fix this by turning off 'SSL certificate verification' in Settings > General
Proxy configured incorrectly
Ensure that proxy is configured correctly in Settings > Proxy
Request timeout:
Change request timeout in Settings > General

我缺少什么?我已经设置了CORS以允许任何来源。如果我在return Ok(products)上设置断点,并取消注释Includes()调用,我可以看到数据被添加到products对象中。

为什么响应会失败?


1
我想响应失败是因为你的代码抛出了异常。尝试进行调试以查看发生了什么。 - SBFrancies
可能您有循环引用。(产品->产品类别->产品) - Nick Polyderopoulos
1个回答

9

这是JSON序列化器的循环引用问题。 您可以通过在Startup.cs文件中添加以下配置来解决该问题:

services.AddMvc()
    .AddJsonOptions(option =>
    {
        option.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    });

正是我所缺少的。非常感谢你! - sadq3377
天啊,那个问题让我浪费了2个小时。 - isebarn
非常感谢您的提示。我知道缺少配置的一部分才能使其正常工作;-) - Insight

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接