Home > Software design >  How to update multiple rows of a database table in ASP.NET Core
How to update multiple rows of a database table in ASP.NET Core

Time:08-17

I want to update multiple rows in ASP.NET Core, but I get an error:

InvalidOperationException: The entity type 'EntityQueryable' was not found. Ensure that the entity type has been added to the model.

This is my code:

var data = _db.UserTable.Where(a => a.CityIDn == selectedid);

foreach (var items in data)
{
    await Task.Run(() =>
                {
                    items.CityID = 2;
                });

    _db.Update(data);
    await _db.SaveChangesAsync();
}

CodePudding user response:

Try this for multiple rows:

var data = _db.UserTable.Where(a => a.CityIDn == selectedid).ToList();

foreach (var item in data)
{
    item.CityID = 2;
    _db.UserTable.Update(item);
}
await _db.SaveChangesAsync();

And for one record, try like this:

var data = _db.UserTable.Where(a => a.CityIDn == selectedid).FirstOrDefault();
if(data != null)
{
    data.CityID = 2;
    _db.UserTable.Update(data );
    await _db.SaveChangesAsync();
}

CodePudding user response:

The content of Update should be items, it worked for me, you can have a try.

var data = _db.UserTable.Where(a => a.CityIDn == selectedid).ToList();
foreach (var items in data)
{
    await Task.Run(() =>
                {
                    items.CityID = 2;
                });

    _db.Update(items);
    await _db.SaveChangesAsync();
}
  • Related