![](/img/trans.png)
[英].Net Core error System.InvalidOperationException: The instance of entity type is already being tracked
[英]Asp.net core System.InvalidOperationException: The instance of entity type x cannot be tracked
我是 asp.net core 的新手,我從 udemy 獲得了一門課程。 我所做的一切都像教練所做的那樣。 當我嘗試將測試數據添加到數據庫時,出現錯誤System.InvalidOperationException: 'The instance of entity type 'ProductCategory' cannot be tracked because another instance with the same key value for {'CategoryId', 'ProductId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'
System.InvalidOperationException: 'The instance of entity type 'ProductCategory' cannot be tracked because another instance with the same key value for {'CategoryId', 'ProductId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'
. 我對此進行了很多研究,但我一無所知,因為它對我來說似乎非常復雜。
種子數據庫.cs
using Entity.Models;
using Microsoft.EntityFrameworkCore;
using ShopApp.Entity.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Data.Concrete.EfCore
{
public static class SeedDatabase
{
public static void seed()
{
var context = new ShopContext();
if (context.Database.GetPendingMigrations().Count() == 0)
{
if (context.Categories.Count() == 0)
{
context.Categories.AddRange(categories);
}
if (context.Products.Count() == 0)
{
context.Products.AddRange(Products);
context.AddRange(ProductCategories);
}
}
context.SaveChanges();
}
private static Category[] categories = {
new Category(){Name="Kağıt"},
new Category(){Name="Kalem"},
new Category(){Name="Sarf Malzemesi"}
};
private static Product[] Products = {
new Product(){Name="A4 Kağıt",price=11.5,quantity=12,CategoryId=0},
new Product(){Name="Faber Kalem",price=7,quantity=54,CategoryId=1},
new Product(){Name="Yazıcı Çarkı",price=3,quantity=87,CategoryId=2},
new Product(){Name="Dosya Kağıdı",price=0.10,quantity=850,CategoryId=0},
new Product(){Name="Rotring Kalem",price=16,quantity=125,CategoryId=1},
new Product(){Name="Toner",price=65,quantity=14,CategoryId=2}
};
private static ProductCategory[] ProductCategories = {
new ProductCategory(){Product=Products[0],Category=categories[0]},
new ProductCategory(){Product=Products[0],Category=categories[1]},
new ProductCategory(){Product=Products[1],Category=categories[0]},
new ProductCategory(){Product=Products[0],Category=categories[1]}
};
}
}
產品.cs
namespace ShopApp.Entity.Models
{
public class Product
{
public int Id { get; set; }
[Required(ErrorMessage ="Lütfen isim giriniz")]
public string Name { get; set; }
[Required(ErrorMessage = "Lütfen fiyat giriniz")]
public double? price { get; set; }
[Required(ErrorMessage = "Lütfen adet giriniz")]
public double? quantity { get; set; }
public string ImageUrl { get; set; }
[Required(ErrorMessage = "Lütfen kategori seçiniz")]
public int? CategoryId { get; set; }
//public Category Category { get; set; }
public List<ProductCategory> ProductCategories { get; set; }
}
}
類別.cs
namespace ShopApp.Entity.Models
{
public class Category
{
public int id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<ProductCategory> ProductCategories { get; set; }
}
}
產品類別.cs
namespace Entity.Models
{
public class ProductCategory
{
public int CategoryId { get; set; }
public Category Category { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
}
}
ShopContext.cs
namespace Data.Concrete.EfCore
{
public class ShopContext:DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("DataSource=ShopDb");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ProductCategory>().HasKey(c => new { c.CategoryId, c.ProductId });
}
}
}
我嘗試創建具有多對多關系的表,這意味着一個產品可能屬於多個類別,一個類別可能屬於多個產品。
當我們按照它的工作方式更改代碼時,它會拋出錯誤,因為在添加范圍類別和產品之后,我必須運行 savechanges(),因為產品和類別必須從數據庫中獲取 ID,然后我們才能標記產品類別。
種子數據庫.cs
namespace Data.Concrete.EfCore
{
public static class SeedDatabase
{
public static void seed()
{
var context = new ShopContext();
if (context.Database.GetPendingMigrations().Count() == 0)
{
if (context.Categories.Count() == 0 && context.Products.Count() == 0)
{
var cats = new List<Category> {
new Category(){Name="Kağıt"},
new Category(){Name="Kalem"},
new Category(){Name="Sarf Malzemesi"}
};
context.Categories.AddRange(cats);
context.SaveChanges();
var prods = new List<Product>{
new Product() { Name = "A4 Kağıt", price = 11.5, quantity = 12, CategoryId = cats[0].id },
new Product() { Name = "Faber Kalem", price = 7, quantity = 54, CategoryId = cats[1].id },
new Product() { Name = "Yazıcı Çarkı", price = 3, quantity = 87, CategoryId = cats[2].id },
new Product() { Name = "Dosya Kağıdı", price = 0.10, quantity = 850, CategoryId =cats[0].id },
new Product() { Name = "Rotring Kalem", price = 16, quantity = 125, CategoryId =cats[1].id },
new Product() { Name = "Toner", price = 65, quantity = 14, CategoryId = cats[2].id }
};
context.Products.AddRange(prods);
context.SaveChanges();
var prodVats = new List<ProductCategory>();
for (int i = 0; i < prods.Count; i++)
{
prodVats.Add(new ProductCategory { CategoryId = prods[i].CategoryId.Value, ProductId = prods[i].Id });
}
context.AddRange(prodVats);
context.SaveChanges();
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.