从ASP.NET Core上传多个文件并存储到数据库中

问题描述

我有这种方法可以上传文件并将文件名称插入数据库。上载到文件夹的工作正常,但插入数据库失败-我收到此错误

当IDENTITY_INSERT设置为OFF时,无法为表“图像”中的标识列插入显式值

代码

if (files != null)
{
    foreach (var file in files)
    {
        if (file.Length > 0)
        {
            //Getting FileName
            var fileName = Path.GetFileName(file.FileName);

            //Assigning Unique Filename (Guid)
            var myUniqueFileName = Convert.ToString(Guid.NewGuid());

            //Getting file Extension
            var fileExtension = Path.GetExtension(fileName);

            // concatenating  FileName + FileExtension
            var newFileName = String.Concat(myUniqueFileName,fileExtension);

            // Combines two strings into a path.
            var filepath =  new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),"wwwroot","Image")).Root + $@"\{newFileName}";

            using (FileStream fs = System.IO.File.Create(filepath))
            {
                file.copyTo(fs);
                fs.Flush();
            }
            image.file= fileName;
            _context.Add(image);
           await _context.SaveChangesAsync();
        }
    }
}

我的EF班Image

public partial class Image
{
    public int ImageId { get; set; }
    public string ImageName { get; set; }
    public string ImageContentType { get; set; }
    public byte[] ImageData { get; set; }
    public bool? IsDelete { get; set; }
    public bool? ImageCover { get; set; }
}

解决方法

将以下内容添加到您的实体:

public partial class Image
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ImageId { get; set; }
    public string ImageName { get; set; }
    public string ImageContentType { get; set; }
    public byte[] ImageData { get; set; }
    public bool? IsDelete { get; set; }
    public bool? ImageCover { get; set; }
}

还有以下选项:

_context.Database.OpenConnection();
try
{
    _context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Images ON");
    await _context.SaveChangesAsync();
    _context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Images OFF");
}
finally
{
    _context.Database.CloseConnection();
}

来源:https://entityframeworkcore.com/saving-data-identity-insert#:~:text=When%20you%20have%20a%20primary,before%20calling%20SaveChanges()%20manually