我最近将我的两个项目都移到了SQLite.net-pcl。到目前为止,我遇到了许多问题,这是我的最新情况。每当我在iOS上运行我的应用程序时,它都会崩溃,并显示SQLite.SQLiteException:约束。Android在同一PCL上运行,并且会在第一次运行,但之后会给我SQLite.SQLiteException:约束,直到删除应用程序存储。不知道还有什么可以在这里尝试。
代码示例:-
宾语
using System; namespace App.LocalObjects { [Preserve(AllMembers = true)] public class LocalArticle { [SQLite.PrimaryKey, SQLite.Column("articleObjectId")] public string objectId { get; set; } public DateTime createdAt { get; set; } public DateTime updatedAt { get; set; } public string Title { get; set; } public string Description { get; set; } public string Url { get; set; } public int Status { get; set; } public LocalArticle() { this.objectId = " "; this.Title = " "; this.Description = " "; this.Url = " "; } } }
数据库
using System; using System.Linq; using System.Collections.Generic; using SQLite; using App.LocalObjects; namespace App.DataLayer { public class Database { static object locker = new object(); public SQLiteConnection database; public string path; public Database(SQLiteConnection conn) { database = conn; database.CreateTable(); } public int SaveLocalArticleItem(LocalArticle item) { lock (locker) { LocalArticle article = database.Table ().FirstOrDefault(x => x.objectId == item.objectId); if (article != null && article.objectId.Equals(item.objectId) && !article.updatedAt.Equals(item.updatedAt)) { database.Update(item); return item.ID; } else { return database.Insert(item); } } }
初始化数据库的代码:
using System; using System.IO; using Android.App; using App.BusinessLayer.Managers; using App.BusinessLayer.ParseObjects; using App.Utils; using Android.Content; using Com.Nostra13.Universalimageloader.Core; using Com.Nostra13.Universalimageloader.Core.Assist; using Android.Graphics; using Com.Nostra13.Universalimageloader.Cache.Memory.Impl; using Com.OneSignal; using Parse; using SQLite; namespace App.Droid { [Application(LargeHeap = true)] public class App : Application { public static App Current { get; private set; } public ModelManager modelManager { get; set; } private SQLiteConnection conn; private ImageLoader imageLoader; public App(IntPtr handle, global::Android.Runtime.JniHandleOwnership transfer) : base(handle, transfer) { Current = this; } public override void OnCreate() { base.OnCreate(); SetupParse(); SetupDB(); } private void SetupParse() { ParseObject.RegisterSubclass(); ParseClient.Initialize(new ParseClient.Configuration { ApplicationId = Constants.ParseApplicationID, Server = Constants.ParseServer }); } private void SetupDB() { var sqliteFilename = Constants.DBName; string libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var path = System.IO.Path.Combine(libraryPath, sqliteFilename); conn = new SQLiteConnection(path); modelManager = new ModelManager(conn); }
这是我的项目当前引用的内容:
好的,所以我找到了一些有关为什么发生这种情况的信息...
因此,SQLiteException:Constraint与是否对表具有UNIQUE,NOT NULL或CHECK约束并且您尝试执行UPDATE或INSERT有关。在此处阅读更多内容SQLite约束
所以我的问题是我有主键(它将始终是唯一的)和不正确的代码正在检查数据库中的项目,而没有更新它,而是试图插入它。由于主键相同,因此引发错误。现在已经解决了。