Search code examples
c#sqlitelinqasp.net-coremodel-view-controller

Update value into SQLite db using C# or LINQ


I have model:

public partial class City
{
    public int Id { get; set; }
    public bool Name { get; set; }
}

DbContext:

public class CityContext : DbContext
{
    public CityContext (DbContextOptions<CityContext> options) : base(options)
    { }

    public DbSet<City> CityDBC { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<City>().HasData(
             new City{ Id = 1, Name = "Rome"},
             new City{ Id = 2, Name = "Londyn"},
             new City{ Id = 3, Name = "Amsterdam"});

        base.OnModelCreating(modelBuilder);
    }
}

Into controller I want to change Name for some City:

public IActionResult Change()
{
var selectedId = 1;
var newName = "Paris";

var checkCountCity = _cityContext.CityDBC.Count();// it's working, I got 3
var changeName = _cityContext.CityDBC.Where(x => x.Id == selectedId);

return RedirectToAction("Home");
}

For DB I'm using SQLite.

How to change now City Name for selected Id ?


Solution

  • You can refer to this code to update record in linq.

     var cityToChange =  _cityContext.CityDBC.Where(x => x.Id == selectedId).FirstOrDefault();
     cityToChange.Name = "new name";
     _cityContext.SaveChanges();