微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决从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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。