我的模型GasStation
using Newtonsoft.Json;
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
namespace TDEv2.Models
{
public class GasStation
{
[JsonProperty("costcentre")]
public string CostCentre { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")][PrimaryKey][AutoIncrement]
public string Id { get; set; }
}
}
和:
using System;
using System.Collections.Generic;
using System.Text;
namespace TDEv2.Models
{
public class GasStationQuery
{
public GasStation[] GasStations { get; set; }
}
}
我的App.xaml.cs
:
using System;
using System.IO;
using TDEv2.Data;
using TDEv2.Views;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace TDEv2
{
public partial class App : Application
{
public static GasStationDatabase database;
public App ()
{
InitializeComponent();
MainPage = new MainPage();
}
public static GasStationDatabase Database
{
get
{
if (database == null)
{
database = new GasStationDatabase(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "GasStationSQLite.db3"));
}
return database;
}
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
}
}
这是我的GasStationDatabase
using SQLite;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using TDEv2.Models;
namespace TDEv2.Data
{
public class GasStationDatabase
{
public SQLiteAsyncConnection database;
public GasStationDatabase(string dbPath)
{
database = new SQLiteAsyncConnection(dbPath);
try
{
database.CreateTableAsync<GasStation>().Wait();
} catch (AggregateException ae)
{
Console.WriteLine("123;" + ae.Flatten().InnerExceptions);
}
}
public Task<List<GasStation>> GetItemsAsync()
{
return database.Table<GasStation>().ToListAsync();
}
public Task<GasStation> GetItemAsync(string id)
{
return database.Table<GasStation>().Where(i => i.Id == id).FirstOrDefaultAsync();
}
public Task<int> SaveItemAsync(GasStation gasStation)
{
if (gasStation.Id != null)
{
return database.UpdateAsync(gasStation);
} else
{
return database.InsertAsync(gasStation);
}
}
}
}
这是我最初用于创建数据库的InitialAsyncGasStationDatabase
。
using Newtonsoft.Json;
using System.Net;
using TDEv2.Models;
namespace TDEv2.Services
{
public class InitialAsyncGasStationDatabase
{
public GasStationQuery InitialAsyncGasStationsToDatabase()
{
string json;
using (WebClient client = new WebClient())
{
json = client.DownloadString($"http://xxx/gasstations.json");
}
var data = JsonConvert.DeserializeObject<GasStationQuery>(json);
foreach (GasStation gasStation in data.GasStations)
{
App.Database.SaveItemAsync(gasStation);
}
return data;
}
}
}
通过调试,我发现我的代码在GasStationDatabase
的{{1}}中停止工作了,正如您所看到的,我试图捕获database.CreateTableAsync<GasStation>().Wait();
,但它只说明了此错误“ System.Collections .ObjectModel.ReadOnlyCollection`1 [System.Exception]”。