'In my controller , How to do foreach of my table PageContent and update only to field inside of each record the records [closed]
i want to update all the records of my table PageContent in my controller. How to do a foreach or for in order to update all the record of my table but only two field i want to update :
fetched.PageContentVisible = false;
fetched.PageContentPhoto = "Submenu" + "-" + item.PageContentId + "-" + item.MenuSubId + "-" + item.PageSectionId;
This is the code :
// GET: PageContents/UpdateScript
public async Task<IActionResult> UpdateScript()
{
using (var transaction = new TransactionScope())
{
var pageContent = _context.PageContent.Include(p => p.ParentMenuPage).Include(p => p.ParentPageSection);
using (_context)
{
foreach (var item in pageContent)
{
var fetched = _context.PageContent.Find(item.PageContentId);
fetched.PageContentPhoto = "PageContent" + "-" + item.PageContentId + "-" + item.MenuSubId + "-" + item.PageSectionId;
if (item.PageSectionId == 2)
{
fetched.PageContentVisible = false;
}
_context.Entry(fetched).State = EntityState.Modified;
//await _context.SaveChangesAsync();
_context.SaveChanges();
}
}
transaction.Complete();
return View(await pageContent.ToListAsync());
}
}
but it does not work because of this error :
ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'ApplicationDbContext'. Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
CateringMilano.Controllers.PageContentsController.UpdateScript() in PageContentsController.cs + return View(await pageContent.ToListAsync());
thanks for your suggestions
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
