简体   繁体   English

无法跟踪实体类型的实例,因为另一个实例...更新数据库时出现 EF Core 错误

[英]The instance of entity type cannot be tracked because another instance… EF Core error when updating db

Service:服务:

public Cart AddProductToCart(Product product, Cart cart)
{
    var productExist = _dbContexet.CartProduct.Where(cp => cp.ProductId == product.Id).FirstOrDefault();
    var quantityOfCart = _dbContexet.CartProduct.Where(cp => cp.CartId == cart.Id).FirstOrDefault().Quantity;

    CartProduct cartProduct = new CartProduct();
    cartProduct.CartId = cart.Id;
    cartProduct.ProductId = product.Id;

    if (productExist != null)
    {
        cartProduct.Quantity = quantityOfCart + 1;
        _dbContexet.Attach(cartProduct).State = EntityState.Modified;
    }
    else
    {
        cartProduct.Cart = cart;
        cartProduct.Product = product;
        _dbContexet.CartProduct.Add(cartProduct);
    }
    _dbContexet.SaveChanges();
    return cart;
}

Full error:完整错误:

InvalidOperationException: The instance of entity type 'CartProduct' cannot be tracked because another instance with the same key value for {'CartId', 'ProductId'} is already being tracked. InvalidOperationException:无法跟踪实体类型“CartProduct”的实例,因为已经在跟踪具有相同键值 {'CartId', 'ProductId'} 的另一个实例。 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.考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看冲突的键值。

I have many to many and table CartProduct I want to check if product exist and only update quantity if it exist but I get this error?我有多对多表CartProduct我想检查产品是否存在,如果存在则只更新数量,但我收到此错误?

Eddit:编辑:

Product:产品:

public partial class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Category { get; set; }
        public decimal CostToMake { get; set; }
        public decimal FinalPrice { get; set; }
        //public int? OrderId { get; set; }

        public virtual Order Order { get; set; }
        public List<CartProduct> CartProduct { get; set; }
    }

Cart:大车:

 public class Cart
        {
            public int Id { get; set; }
    
            public int ProductCount { get; set; }
    
            public AppUser User { get; set; }
    
            public List<CartProduct> CartProduct { get; set; }
        }

CartProduct:购物车产品:

public class CartProduct
    {
        public int CartId { get; set; }
        public int ProductId { get; set; }

        public Cart Cart { get; set; }
        public Product Product { get; set; }

        public int Quantity { get; set; }
    }

FluentAPI:流利的API:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.HasAnnotation("Relational:Collation", "Cyrillic_General_CI_AS");

            modelBuilder.Entity<Day>(entity =>
            {
                entity.Property(e => e.Date).HasColumnType("date");

                entity.Property(e => e.MostCommonCategory)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.MostCommonProduct)
                    .IsRequired()
                    .HasMaxLength(100)
                    .IsUnicode(false);

                entity.Property(e => e.TotalMade).HasColumnType("decimal(18, 3)");

                entity.Property(e => e.TotalSpent).HasColumnType("decimal(18, 3)");
            });

            modelBuilder.Entity<Order>(entity =>
            {
                entity.Property(e => e.Date).HasColumnType("date");               

                entity.Property(e => e.Status)
                    .IsRequired()
                    .HasMaxLength(100)
                    .IsUnicode(false);

                entity.Property(e => e.Name).HasMaxLength(100);

                entity.Property(e => e.Address).HasMaxLength(150);

                entity.Property(e => e.PhoneNumber).HasMaxLength(20);
            });

            modelBuilder.Entity<Product>(entity =>
            {
                entity.HasIndex(e => e.OrderId, "IX_Products_OrderId");

                entity.Property(e => e.Category)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.CostToMake).HasColumnType("decimal(18, 3)");

                entity.Property(e => e.FinalPrice).HasColumnType("decimal(18, 3)");

                entity.Property(e => e.Name)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.Price).HasColumnType("decimal(18, 3)");

                entity.HasOne(d => d.Order)
                    .WithMany(p => p.Products)
                    .HasForeignKey(d => d.OrderId);
            });

            modelBuilder.Entity<Cart>(entity => {
                entity.HasKey(e => e.Id);
                entity.HasOne(e => e.User)
                .WithOne(e => e.Cart)
                .HasForeignKey<AppUser>(e => e.CartId);
            });

            modelBuilder.Entity<CartProduct>()
            .HasKey(e => new { e.CartId, e.ProductId });

            modelBuilder.Entity<CartProduct>()
            .HasOne(t => t.Cart)
            .WithMany(t => t.CartProduct)
            .HasForeignKey(t => t.ProductId);

            modelBuilder.Entity<CartProduct>()
            .HasOne(t => t.Product)
            .WithMany(t => t.CartProduct)
            .HasForeignKey(t => t.CartId);

            OnModelCreatingPartial(modelBuilder);
        }

You can perform some actions but in a different way, using EF features.您可以使用 EF 功能以不同的方式执行某些操作。

public Cart AddProductToCart(Product product, Cart cart)
{
  var product = _dbContexet.Product.Where(cp => cp.ProductId == product.Id).Include(x => x.CartProduct).FirstOrDefault();
  var quantityOfCart = _dbContexet.CartProduct.Where(cp => cp.CartId == cart.Id).FirstOrDefault().Quantity;
  var cartProduct = product.CartProduct.Where(x=>x.CartId == cart.id).FirstOrDefault();

  if (cartProduct != null)
  {
    cartProduct.Quantity = quantityOfCart + 1;
  }
  else
  {
     product.CartProduct.Add(new CartProduct { CartId = cart.id });
  }

  //_dbContexet.Update(product) if you are using QueryTrackingBehavior.NoTracking
  _dbContexet.SaveChanges();
  return cart;
}

Your error is because:你的错误是因为:

 cartProduct.CartId = cart.Id;
 cartProduct.ProductId = product.Id;

in reallity is the same as:实际上是一样的:

 cartProduct.Cart = cart;
 cartProduct.Product = product;

so just remove from your code:所以只需从您的代码中删除:

 cartProduct.Cart = cart;
 cartProduct.Product = product;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 EF Core:无法跟踪实体类型的实例,因为另一个实例具有相同的键值 - EF Core: The instance of entity type cannot be tracked because another instance with the same key value EF Core(内存数据库)-'无法跟踪实体类型 X 的实例,因为另一个具有键值的实例 - EF Core (in-memory database) - 'The instance of entity type X cannot be tracked because another instance with the key value EF 错误:无法跟踪实体类型“对象”的实例,因为另一个实例 - EF error: The instance of entity type 'Object' cannot be tracked because another instance EF:无法跟踪实体类型X的实例,因为已经跟踪了具有相同密钥的此类型的另一个实例 - EF: The instance of entity type X cannot be tracked because another instance of this type with the same key is already being tracked 实体框架核心 - 无法跟踪实体类型的实例,因为已在跟踪具有键值的另一个实例 - Entity framework Core - The instance of entity type cannot be tracked because another instance with the key value is already being tracked 错误:无法跟踪实体类型“X”的实例,因为已在跟踪另一个具有键值“{ID:3}”的实例 - Error: The instance of entity type 'X' cannot be tracked because another instance with the key value '{ID: 3}' is already being tracked Entity framework core 无法跟踪实体类型的实例,因为另一个实例具有相同的键值 - Entity framework core The instance of entity type cannot be tracked because another instance with the same key value Entity Framework Core:无法跟踪实体类型的实例,因为另一个实例具有相同的键值 - Entity Framework Core : instance of entity type cannot be tracked because another instance with same key value 实体框架核心 - 无法跟踪实体类型的实例,因为已在跟踪具有相同键的此类型的另一个实例 - Entity Framework core - The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked InvalidOperationException:无法跟踪实体类型“Vessels”&gt; 的实例,因为另一个实例 - InvalidOperationException: The instance of entity type 'Vessels' > cannot be tracked because another instance
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM