使用C#或LINQ将值更新到SQLite数据库中

gblwokeq  于 2023-03-19  发布在  SQLite
关注(0)|答案(2)|浏览(134)

我有型号:

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

数据库上下文:

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);
    }
}

进入控制器,我想将一些City更改为Name

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");
}

对于数据库,我使用SQLite
如何立即更改所选ID城市名称**?

hrirmatl

hrirmatl1#

你可以参考这段代码来更新linq中的记录。

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

c7rzv4ha2#

看起来您使用的是实体框架,因此要更新数据,您需要获取要更改的实体,更新它并保存更改:

var cityToChange = _cityContext.CityDBC.Single(x => x.Id == selectedId);
cityToChange.Name = newName;
_cityContext.SaveChanges();

此外,我建议使用异步对应项(SingleAsyncSaveChangesAsync、使用await并将方法声明更改为async Task<IActionResult>),并可能将Single更改为SingleOrDefault(或FirstOrDefault,取决于目标),如果结果为null,则返回not found。

相关问题