I get this error:
SqlException: Cannot insert explicit value for identity column in table 'imageClasses' when IDENTITY_INSERT is set to OFF. DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
SqlException: Cannot insert explicit value for identity column in table 'imageClasses' when IDENTITY_INSERT is set to OFF.
Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, bool breakConnection, Action wrapCloseInAction)
DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
This is my code:
public class ImageClass
{
public string imgName { get; set; }
public string imgExt { get; set; }
public string imgPath { get; set; }
}
public class _2_MultipleImagesController : Controller
{
private readonly IWebHostEnvironment iweb;
private readonly ImageDbContext db;
public _2_MultipleImagesController(IWebHostEnvironment i , ImageDbContext db)
{
iweb = i;
this.db = db;
}
public IActionResult Index()
{
var list = db.imageClasses.ToList();
return View(list);
}
[HttpPost]
public IActionResult Index(IFormFile[] fileObj, ImageClass ic)
{
if (fileObj != null)
{
foreach (IFormFile img in fileObj)
{
string imgExt = Path.GetExtension(img.FileName);
if (imgExt == ".jpg" || imgExt == ".svg" || imgExt == ".png")
{
var imgSave = Path.Combine(iweb.WebRootPath, "MultipleImages", img.FileName);
using (Stream st = new FileStream(imgSave, FileMode.Create))
{
img.CopyTo(st);
}
ic.imgName = img.FileName;
ic.imgExt = imgExt;
ic.imgPath = imgSave;
db.imageClasses.Add(ic);
}
}
}
db.SaveChanges();
return RedirectToAction("Index");
}
}
And my markup:
<div class="container">
<div class="row">
@foreach (var item in Model)
{
<div class="col-3 text-center">
<div class="alert alert-secondary">
<img src="~/MultipleImages/@item.imgName" width="180" height="160" />
</div>
</div>
}
</div>
</div>
<br />
<form enctype="multipart/form-data" asp-action="index" asp-controller="_2_MultipleImages">
<div class="row">
<div class="col-6">
<input type="file" name="fileObj" multiple class="form-control" />
</div>
<div class="col-6">
<input type="submit" value="insert" class="btn btn-primary" />
</div>
</div>
</form>