Entity Framework Core尝试在调用SaveChanges()时插入重复的记录(Entity Framework Core is trying to insert duplicated

编程入门 行业动态 更新时间:2024-10-25 18:29:43
Entity Framework Core尝试在调用SaveChanges()时插入重复的记录(Entity Framework Core is trying to insert duplicated records when SaveChanges() is called)

我的实体是:

public class Customer { ... public virtual ICollection<ShoppingCartItem> ShoppingCartItems { get; set; } ... } public class ShoppingCartItem { public string CustomerId { get; set; } public int ProductId { get; set; } public virtual Customer { get; set; } public virtual Product{ get; set; } ... }

add方法是:

public async Task AddAsync(TEntity entity) { await Task.Factory.StartNew(() => this.entities.Add(entity)); }

我要添加的实体是:

ShoppingCartItem() { CustomerId = "xxxxx", ProductId = 1, Customer = null, Product = null }

当我调用SaveChanges()时,EF正在尝试为ShoppingCartItem插入两个相同的记录。 ShoppingCartItem只创建一次并添加到上下文中。 什么可能是错的想法?

编辑:

这就是我调用AddSync方法的方法:

public async Task AddNewCartItem(ShoppingCartItem shopingCartItem) { await this.ShoppingCartItemRepository.AddAsync(shopingCartItem); await this.SmartStoreWorkData.CompleteAsync(); }

My Entities are:

public class Customer { ... public virtual ICollection<ShoppingCartItem> ShoppingCartItems { get; set; } ... } public class ShoppingCartItem { public string CustomerId { get; set; } public int ProductId { get; set; } public virtual Customer { get; set; } public virtual Product{ get; set; } ... }

The add method is:

public async Task AddAsync(TEntity entity) { await Task.Factory.StartNew(() => this.entities.Add(entity)); }

The entity that I am adding is:

ShoppingCartItem() { CustomerId = "xxxxx", ProductId = 1, Customer = null, Product = null }

When I call SaveChanges() the EF is trying to insert two identical records for ShoppingCartItem. The ShoppingCartItem is created and added to the context only once. Any ideas what possibly could be wrong?

EDIT:

This is how I call the AddSync method:

public async Task AddNewCartItem(ShoppingCartItem shopingCartItem) { await this.ShoppingCartItemRepository.AddAsync(shopingCartItem); await this.SmartStoreWorkData.CompleteAsync(); }

最满意答案

更新:我做了以下事情:

克隆您的repo链接: SmartStoreNETCore 使用新的EF工具迁移到.NET Core 1.1(preview4) 添加了下面的EF ModelBuilder中指定的配置 应用迁移和更新的数据库

命令:

dotnet ef --startup-project ../SmartStoreNetCore.Web/ migrations add ChangeShoppingCartItemKey dotnet ef --startup-project ../SmartStoreNetCore.Web/ database update

删除了_Layout.cshtml的以下重复标记

<script src="~/js/site.js" asp-append-version="true"></script>

site.js包含“ 添加到购物车”功能的单击事件处理程序

启动网站, 一切按预期工作,没有重复的购物车项目,数量按预期更新

在此处输入图像描述

综上所述

我可以完全确认在删除对site.js的重复引用之前,已调用以下方法两次

public async Task AddNewCartItem(ShoppingCartItem shopingCartItem) { await this.ShoppingCartItemRepository.AddAsync(shopingCartItem); await this.SmartStoreWorkData.CompleteAsync(); }

对我来说,为什么在调试前没有发现这个问题,这是一种谜

EF ModelBuilder

您的配置应如下所示:

builder.Entity<ShoppingCartItem>().HasKey(x => x.Id); // Notice this! builder.Entity<ShoppingCartItem>().Property(x => x.Id).ValueGeneratedOnAdd(); // Also this! builder.Entity<ShoppingCartItem>().HasOne(s => s.Customer).WithMany(b => b.ShoppingCartItems).OnDelete(DeleteBehavior.Restrict); builder.Entity<ShoppingCartItem>().HasOne(s => s.Product).WithMany().OnDelete(DeleteBehavior.Restrict);

拥有自动生成的值不会将其定义为主键

UPDATE: I did the following:

Cloned your repo link: SmartStoreNETCore Migrated to .NET Core 1.1 with the new EF tooling (preview4) Added the configuration as specified in EF ModelBuilder below Applied Migration and updated database

Commands:

dotnet ef --startup-project ../SmartStoreNetCore.Web/ migrations add ChangeShoppingCartItemKey dotnet ef --startup-project ../SmartStoreNetCore.Web/ database update

Removed the following duplicate tag in _Layout.cshtml

<script src="~/js/site.js" asp-append-version="true"></script>

site.js contains the click event handler for the Add To Cart functionality

Started the site and everything worked as expected, no duplicate shopping cart items and the quantity is updated as expected

enter image description here

In summary

I can fully confirm the following method was being called twice before removing the duplicate reference to site.js:

public async Task AddNewCartItem(ShoppingCartItem shopingCartItem) { await this.ShoppingCartItemRepository.AddAsync(shopingCartItem); await this.SmartStoreWorkData.CompleteAsync(); }

It is a mistery to me why you didn't catch this before via debugging

EF ModelBuilder

Your configuration should look like:

builder.Entity<ShoppingCartItem>().HasKey(x => x.Id); // Notice this! builder.Entity<ShoppingCartItem>().Property(x => x.Id).ValueGeneratedOnAdd(); // Also this! builder.Entity<ShoppingCartItem>().HasOne(s => s.Customer).WithMany(b => b.ShoppingCartItems).OnDelete(DeleteBehavior.Restrict); builder.Entity<ShoppingCartItem>().HasOne(s => s.Product).WithMany().OnDelete(DeleteBehavior.Restrict);

Having a value generated automatically does not define it as the primary key

更多推荐

ShoppingCartItem,public,The,entity,电脑培训,计算机培训,IT培训"/> <meta name=

本文发布于:2023-08-02 18:55:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1380641.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Core   SaveChanges   Entity   Framework   records

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!