【发布时间】:2017-12-24 19:14:18
【问题描述】:
我的应用中有多个 ObservableCollections,我想对其进行保存、编辑等操作。但由于它们是我自己的类的集合,SQLite 无法识别它们。保存论文的最佳方法是什么?或者我做错了什么。
有点像这样:
在我的App中:(当然里面还有更多代码)
public partial class App : Application
{
static MyDatabase database;
public static MyDatabase Database
{
get
{
if (database == null)
{
database = new MyDatabase(DependencyService.Get
<IFileHelper>().GetLocalFilePath("MyListSQLite.db3"));
}
return database;
}
}
}
我的数据库:
public class MyDatabase
{
readonly SQLiteAsyncConnection database;
public MyDatabase(string dbPath)
{
database = new SQLiteAsyncConnection(dbPath);
database.CreateTableAsync<MyClass>().Wait();
}
public Task<List<MyClass>> GetItemsAsync()
{
return database.Table<MyClass>().ToListAsync();
}
public Task<MyClass> GetItemAsync(int id)
{
return database.Table<MyClass>().Where(i => i.ID == id).FirstOrDefaultAsync();
}
public Task<int> SaveItemAsync(MyClass item)
{
if (item.ID != 0)
{
return database.UpdateAsync(item);
}
else
{
return database.InsertAsync(item);
}
}
public Task<int> DeleteItemAsync(MyClass item)
{
return database.DeleteAsync(item);
}
}
我的班级:
public class MyClass : ObservableCollection<MyOtherClass>
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
}
我的其他类:
public class MyOtherClass : BindableObject
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public static readonly BindableProperty ListNbrProperty =
BindableProperty.Create("ListNbr", typeof(int), typeof(MyOtherClass), default(int));
public int ListNbr
{
get { return (int)GetValue(ListNbrProperty); }
set { SetValue(ListNbrProperty, value); }
}
public bool IsMaster { get; set; }
public static readonly BindableProperty ResizedPathProperty =
BindableProperty.Create("ResizedPath", typeof(String), typeof(MyOtherClass), default(String));
public String ResizedPath
{
get { return (String)GetValue(ResizedPathProperty); }
set { SetValue(ResizedPathProperty, value); }
}
...
}
【问题讨论】:
-
我想这不是最好的方法。似乎您想保存 MyOtherClass 对象-一旦您的收藏没有理由存在,除了展示您的对象(只是为了展示或处理某些东西)-因此您可以使用
database.InsertAll或database.UpdateAll在您的数据库类。
标签: database sqlite xamarin.forms observablecollection