gpt4 book ai didi

c# - ASP.NET Core 2.2 在多对多插入时返回 "NotSupportedException: Collection was of a fixed size"

转载 作者:行者123 更新时间:2023-12-05 06:26:35 26 4
gpt4 key购买 nike

当我尝试插入ASP 中的多对多 链接表时,出现“NotSupportedException: Collection was of a fixed size”。 NET 核心 2.2。我可以在 SQL Server 中手动插入值!

我的实体是:

    public class Product
{
[key]
public int Id {get;set;}

public ICollection<ProductCategory> ProductCategories { get; set; } = new List<ProductCategory>();
}
    public class Category
{
[key]
public int Id {get;set;}

public string Name { get; set; }

public ICollection<ProductCategory> ProductCategories { get; set; } = new List<ProductCategory>();

}
    public class ProductCategory
{
[Key]
public int ProductId { get; set; }
public Product Product { get; set; }

[Key]
public int CategoryId { get; set; }
public Category Category { get; set; }
}

在 DbContext 中:

        protected override void OnModelCreating(ModelBuilder modelBuilder)
{

modelBuilder.Entity<ProductCategory>().HasKey(t => new { t.ProductId, t.CategoryId });


modelBuilder.Entity<ProductCategory>()
.HasOne(bc => bc.Product)
.WithMany(b => b.ProductCategories)
.HasForeignKey(bc => bc.ProductId);

modelBuilder.Entity<ProductCategory>()
.HasOne(bc => bc.Category)
.WithMany(c => c.ProductCategories)
.HasForeignKey(bc => bc.CategoryId);

base.OnModelCreating(modelBuilder);
}

public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<ProductCategory> ProductCategories {get; set;}

我尝试向 Product 和 Category 插入记录,插入的记录没有问题。但是,当我尝试插入链接记录时,我得到了 "NotSupportedException: Collection was of a fixed size" 错误。

插入:

            var Electronics = new Category
{
Name = "Electronics",
};

var Exir = new Product
{
Name = "Exir",
};

var pc1 = new ProductCategory();

bc1.Product = Exir ;
bc1.Category = Electronics;
Exir.ProductCategories.Add(pc1);

sqlContext.Categories.Add(Electronics);
sqlContext.Products.Add(Exir);
sqlContext.SaveChanges();

最佳答案

当使用固定大小的数据结构(如空数组)初始化集合属性时,可能会发生此错误。

关于c# - ASP.NET Core 2.2 在多对多插入时返回 "NotSupportedException: Collection was of a fixed size",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55983982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com