Xamarin Forms SQLite 更新

Xamarin Forms SQLite Update

我已经安装了 nuget 包 sqlite-net-pcl,我想根据按钮上的文本插入或更新:

 SQLiteConnection database = DependencyService.Get<ISQLite>().GetConnection();
 database.CreateTable<Announcement>(); 
 var announcement = new Announcement { AnnouncementTitle = Title, AnnouncementDate = Date, AnnouncementText = Message };
 if (text == "Save") {
     if (database.Insert(announcement) != -1) {
         System.Diagnostics.Debug.WriteLine("INSERTED");
     }

 }
 else {
    if (database.Update(announcement) > 0) {
       System.Diagnostics.Debug.WriteLine("UPDATED");
    }
 }

当我想保存它时打印 INSERTED 并且我可以在我的列表中看到新项目但是当它更新时它不打印任何东西而且我没有收到错误。我也尝试了异步方法,但它没有用

谢谢

既然要更新,就必须先从数据库中获取原始条目。现在您没有输入 Id 字段(或者它在您的模型中的调用方式),因此它不知道要更新什么。

更新你的代码来做这样的事情,注意:这是伪代码,因为我遗漏了你的模型的一些细节和 SQLite 的相关知识。

 SQLiteConnection database = DependencyService.Get<ISQLite>().GetConnection();
 database.CreateTable<Announcement>(); 
 var announcement = new Announcement { AnnouncementTitle = Title, AnnouncementDate = Date, AnnouncementText = Message };
 if (text == "Save") {
     if (database.Insert(announcement) != -1) {
         System.Diagnostics.Debug.WriteLine("INSERTED");
     }

 }
 else {
    var announcementToUpdate = database.Query<Customer>($"SELECT * FROM Announcement WHERE Id = '{originalId}'").

    // update your 'announcementToUpdate' object with new values here

    if (database.Update(announcementToUpdate) > 0) {
       System.Diagnostics.Debug.WriteLine("UPDATED");
    }
 }

originalId 应该是一个变量,其中包含您要编辑的 ID 的声明。

所以这里更新的关键是你必须先从数据库中检索记录。 使用您要更新的记录的 Id 创建一个新对象。

您的对象公告中需要一个主键或 Id

[PrimaryKey, AutoIncrement]
public int Id { get; set; }

识别您在数据库中的唯一对象。

在您的代码中,您总是创建一个没有 ID 的新对象。 SQLite 看到它并在数据库中为您创建一个新的 Id。但是,如果 Id 为空,则更新无效。

如果您想更新它,您必须使用正确的 Id 从数据库中加载它,然后您可以编辑和更新它。