【问题标题】:How correctly use Include in EF Core [duplicate]如何正确使用包含在 EF Core [重复]
【发布时间】:2021-01-12 11:59:35
【问题描述】:

我有模型

public class ProductModel
{
    public int ProductId { get; set; }
    
    public int BrandId { get; set; }
    [ForeignKey("BrandId")]
    public virtual BrandModel Brand { get; set; }
}

public class BrandModel
{
    public int BrandId { get; set; }
    public string BrandName { get; set; }
   
    public ProductModel Product { get; set; }
}

我的背景

public class ApplicationContext : DbContext
{
    public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
    {
    }
    public DbSet<BrandModel> Brand { get; set; }
    public DbSet<ProductModel> Product { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<BrandModel>().ToTable("Brand").HasKey(k=>k.BrandId);
        modelBuilder.Entity<BrandModel>().Property(p => p.BrandId).IsRequired().HasMaxLength(30);

        modelBuilder.Entity<ProductModel>().ToTable("Product").HasKey(k => k.ProductId);

        modelBuilder.Entity<ProductModel>()
            .HasOne<BrandModel>(p => p.Brand)
            .WithOne(b => b.Product)
            .HasForeignKey<ProductModel>(pr => pr.BrandId);
    }
}

我想带品牌的产品。 1 个产品有 1 个品牌 然后我用include做了简单的方法

var result = await _context.Product.Include(x => x.Brand).ToListAsync();

我看到数据库中的数据,但是有一个循环

System.Text.Json.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.

它找到具有品牌的产品,但该品牌具有具有品牌模型的产品模型......

如何消除此循环并获得带有品牌的产品?

【问题讨论】:

标签: .net asp.net-core .net-core entity-framework-core


【解决方案1】:

这是由对象嵌套或ef查询的预加载(关联加载)造成的,就像“对象循环”解释的那样,层次结构太深而无法解析。

添加 nuget 包

Microsoft.AspNetCore.Mvc.NewtonsoftJson

在启动时添加配置

services.AddControllers().AddNewtonsoftJson(option =>
            //Ignore circular references
            option.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        );

【讨论】:

    猜你喜欢
    • 2020-03-19
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 2020-02-24
    • 2017-09-22
    相关资源
    最近更新 更多