【发布时间】: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.
它找到具有品牌的产品,但该品牌具有具有品牌模型的产品模型......
如何消除此循环并获得带有品牌的产品?
【问题讨论】:
-
this 回答你的问题了吗?
-
另外,如果您不想切换到 Json.Net - .NET 5 现在支持 reference loop handling
标签: .net asp.net-core .net-core entity-framework-core