如何使用 Linq for Entity Framework Core 更新 table 中的多条记录

How to update multiple records in a table Using the Linq for Entity Framework Core

我目前面临更新数据库中多条记录的问题。我想在用户付款时创建收据时更新用户创建的项目列表。

这是我更新它们的API方法。

[HttpPut("update-items")]
public ActionResult UpdateListOfItems(IEnumerable<ItemUpdateDTO> itemUpdateDTOs)
{
    if(itemUpdateDTOs == null)
    {
        return BadRequest();
    }

    var items = _mapper.Map<IEnumerable<Item>>(itemUpdateDTOs);
    _repository.UpdateRangeItem(items);

    return Ok("Updated items!");
}

这是我的项目更新 DTO

public class ItemUpdateDTO
{
    [Required]
    public int ID { get; set; }
    public FishUpdateDTO Fish { get; set; }
    [Required]
    public ReceiptUpdateDTO Receipt { get; set; }
}

这是 table“项目”

的实体模型
public class Item
{
    [Key]
    public int ID { get; set; }
    [Required]
    public int FishID { get; set; }
    public Fish Fish { get; set; }
    [Required]
    public int QuantityOrdered { get; set; }
    [Required]
    public float TotalPrice { get; set; }
    public Receipt Receipt { get; set; }
    public User Customer { get; set; }
}

这是“类别”的实体模型

public class FishCategory
{
    [Key]
    [Required]
    public int ID { get; set; }
    [Required]
    [MaxLength(50)]
    public string Category { get; set; }
    public IEnumerable<Fish> Fish { get; set; }
}

这是存储库方法。

public void UpdateRangeItem(IEnumerable<Item> items)
{
    _databaseContext.Items.UpdateRange(items);
    _databaseContext.SaveChanges();
}

这是项目 table:

和收据table:

我正在尝试使用收据 ID 作为项目 table 中的外键来更新项目 table。但是,我得到一个错误:

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_Fishes_Categories_CategoryID". The conflict occurred in database "EFishing", table "dbo.Categories", column 'ID'.

目前,我正在使用名为 UpdateRange()DatabaseContext 方法在对数据库的一次调用中更新一系列行。

任何解决方案都可以。谢谢

该问题与一次多次更新项目无关。

正如 SQL 服务器告诉您的那样,它与鱼和类别有关。

可能您的一个或多个项目上有一条鱼,这条鱼指向一个不存在的 FishCategory,因此违反了外键。

未设置但定义为不可为空的外键将采用值“0”(整数的默认值),如果您的 ID 从 1 开始,也会以同样的方式失败。也许可为空的 FK 可能会有所帮助(如果它在数据方面有意义)。

验证您的数据库结构和您尝试保存的数据:项目的鱼 属性 和鱼的类别。

所以我知道已经晚了,但这是解决我问题的答案。

因为这个问题 ->

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_Fishes_Categories_CategoryID". The conflict occurred in database "EFishing", table "dbo.Categories", column 'ID'.

这是因为我的类别 table 中不存在特定的类别 ID,因此引发了该错误。编译器产生的错误可能不包含有用的消息,但会检查您 post(可能使用 Postman)的数据,请检查您的实体与之相关的相关数据是否存在。

例如,如果我有

类别Table |类别ID |类别 | | ------ | -------------- | | 1|盐水| | 2|淡水|

这是鱼 table |鱼号|名称|类别编号| |:---- |:------:| -----:| | 1|三文鱼| 1| 但是在 Postman 或您使用的任何软件中,如果您 post 将“Fish”数据 table 的“CategoryID”设置为 post 3、会出现错误,打印如上。因此,请确保类别 table.

中存在“CategoryID: 3”

感谢@AFract。他在一些容易出错的可能性中的回答高于我的回答。