繁体   English   中英

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

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

服务:

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;
}

完整错误:

InvalidOperationException:无法跟踪实体类型“CartProduct”的实例,因为已经在跟踪具有相同键值 {'CartId', 'ProductId'} 的另一个实例。 附加现有实体时,请确保仅附加一个具有给定键值的实体实例。 考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看冲突的键值。

我有多对多表CartProduct我想检查产品是否存在,如果存在则只更新数量,但我收到此错误?

编辑:

产品:

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; }
    }

大车:

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

购物车产品:

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; }
    }

流利的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);
        }

您可以使用 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;
}

你的错误是因为:

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

实际上是一样的:

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

所以只需从您的代码中删除:

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM