gpt4 book ai didi

c# - 将多个更改保存到数据库

转载 作者:太空宇宙 更新时间:2023-11-03 20:50:29 25 4
gpt4 key购买 nike

我正在使用 .Net Core MVC 并且出于某种原因,当我尝试使用循环一次将一堆文件保存到数据库时,我收到此错误:

SqlException: Cannot insert explicit value for identity column in table 'Movie' when IDENTITY_INSERT is set to OFF.

从搜索来看,这似乎通常是在您尝试手动设置 Id 时生成的,但这不是我正在做的。这是我的代码:

foreach (var item in files)
{
string path = item.ToString();
string title = path.Replace(remove[0] + remove[1], "");
movie.IMDBId = 0123;
movie.Title = title;
movie.FilePath = path;
movie.Year = "2007";
_context.Add(movie);
_context.SaveChanges();
}

出于某种原因,这将保存目录中的第一项,然后给出错误。任何帮助将不胜感激,因为我已经搜索了几个小时并且没有找到解决此问题的方法。

编辑 - 电影模型

public class Movie
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("LibraryID")]
public virtual Library Library { get; set; }
public int IMDBId { get; set; }
public string Title { get; set; }
public string Year { get; set; }
public string Genre { get; set; }
public string Description { get; set; }
public string PosterPath { get; set; }
public string FilePath { get; set; }
}

最佳答案

简短回答:您应该将您的 movie 变量定义移动到本地 for 循环范围内。

详细答案:

由于您的变量 movie 是在循环之外的某处定义的,因此每个文件都会重复使用它。第一次运行

_context.Add(movie);
_context.SaveChanges();

您在数据库中创建对象, Entity Framework 更新对象 movie,设置主键和所有其他字段。第二次运行此代码时,EF 再次尝试插入具有相同主键的对象,因此出现错误。

示例解决方案:

foreach (var item in files)
{
string path = item.ToString();
string title = path.Replace(remove[0] + remove[1], "");
var newMovie = new Movie
{
IMDBId = 0123,
Title = title,
FilePath = path,
Year = "2007"
};
_context.Add(newMovie);
_context.SaveChanges();
}

关于c# - 将多个更改保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55880914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com