不能使用多个表。如何处理两张、三张或更多张桌子?
Visual >>> Xamarin-Forms
/// I think maybe this code needs to be fixed somehow.
/// this code is placed in App.cs (up)
static Data.TableTwo tabletwo;
static Data.TableOne tableone;/// crashed
public Task<int> SaveItemAsync(TableTwo item)
{
if (item.ID != 0)
{
return tabletwo.UpdateAsync(item);
}
else
{
return tabletwo.InsertAsync(item);
}
} /// ***I think maybe this code needs to be fixed somehow.
/// this code is placed in App.cs (down below)
public static Data.TableTwo tabletwo
{
get
{
if (datadistance == null)
{
tabletwo = new Data.TableTwo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TodoSQLite.db3"));
}
return tabletwo;
}
}/// ***I think maybe this code needs to be fixed somehow.
/// this code is placed in App.cs (down below)
public static Data.TableOne tableone
{
get
{
if (tableone == null)
{
tableone = new Data.TableOne(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TodoSQLite.db3"));
}
return tableone;
}
}以上代码工作正常。当上面的代码被调用时。申请失败。
我有两张桌子。在用户工作时,使用一个表(保存和删除数据),那么所有操作都正常。如果用户开始使用另一个表(保存数据),应用程序就会崩溃。
应用程序树!DataBase(文件夹)TableTwo(文件)TableOne(文件)模型(文件夹)TableTwo(文件)TableOne(文件)
所有的事情都是按照https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/databases#using-sqlite文章中的代码做的
实际上,我只是第二次复制了代码,然后粘贴到了项目中。-这就是我所做的,创建第二个表并使用它(删除插入数据)
发布于 2019-03-29 19:19:45
让我们假设您的两个表类型为Load和MyDatabase,数据库的类型为MyDatabase,您可能希望在MyDatabase类中保持到SqlLite的单个连接,并添加与表交互的方法,如下所示:
public class MyDatabase
{
private readonly SQLiteAsyncConnection _connection;
public MyDatabase():this(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyDatabase.db3"))
{
}
internal MyDatabase(string dbPath)
{
_connection = new SQLiteAsyncConnection(dbPath);
_connection.CreateTableAsync<Load>().Wait();
_connection.CreateTableAsync<Category>().Wait();
}
public Task<List<Load>> GetLoads() =>
_connection.Table<Load>().ToListAsync();
public Task<List<Category>> GetCategories() =>
_connection.Table<Category>().ToListAsync();
public Task<Load> GetLoad(int id) =>
_connection.Table<Load>().Where(i => i.Id == id).FirstOrDefaultAsync();
public Task<int> SaveLoad(Load item) =>
item.Id != 0 ? _connection.UpdateAsync(item) : _connection.InsertAsync(item);
public Task<int> DeleteLoad(Load item) =>
_connection.DeleteAsync(item);
}下面是一个很好的示例:https://github.com/xamarin/xamarin-forms-samples/blob/master/Todo/Todo/Data/TodoItemDatabase.cs,但是它包含一个表
https://stackoverflow.com/questions/55421432
复制相似问题