我有兴趣将 SQlite-Net 扩展 ( https://bitbucket.org/twincoders/sqlite-net-extensions ) 与 Xamarin Forms 一起使用。我正在使用 Visual Studio 2013、NuGet 的 SQlite.Net PCL 2.3.0 和空白的 Hello World Xamarin Forms PLC 项目。作为第一步,我尝试从 Sqlite.Net 扩展站点获取示例。根据 Xamarin 网站上建议的方法,我使用 DependencyService 来获取 SQLIteConnection。但是,我的代码甚至无法编译,因为它在 SQLiteConnection 上找不到 UpdateWithChildren 或 GetWithChildren 方法。很明显,我的 SQLiteConnection 对象并不具有与示例相同的内容。我是否使用了错误的 SQLite.Net PCL 库? Xamarin 和 SQLite-Net Extensions 都建议使用 NuGet 中的 PCL 版本,这就是我认为我拥有的...
我也在 Xamarin 论坛上发布了此内容: http://forums.xamarin.com/discussion/20117/sqlite-net-extensions-and-sqliteconnection#latest
这是我的代码(ISQLite 类除外)。 数据模型:
using SQLiteNetExtensions.Attributes;
using SQLite.Net.Attributes;
namespace Sample.Models
{
public class Stock
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(8)]
public string Symbol { get; set; }
[OneToMany] // One to many relationship with Valuation
public List<Valuation> Valuations { get; set; }
}
public class Valuation
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[ForeignKey(typeof(Stock))] // Specify the foreign key
public int StockId { get; set; }
public DateTime Time { get; set; }
public decimal Price { get; set; }
[ManyToOne] // Many to one relationship with Stock
public Stock Stock { get; set; }
}
}
这是我的 DatabaseHelper。现在我只是在构造函数中运行测试。我得到的错误是找不到 UpdateWithChildren 和 GetWithChildren 方法。
using Sample.Models;
using SQLite.Net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Sample.Orm
{
class DatabaseHelper
{
private SQLiteConnection db;
public DatabaseHelper()
{
db = DependencyService.Get<ISQLite>().GetConnection();
//Create the tables
db.CreateTable<Stock>();
db.CreateTable<Valuation>();
var euro = new Stock()
{
Symbol = "€"
};
db.Insert(euro); // Insert the object in the database
var valuation = new Valuation()
{
Price = 15,
Time = DateTime.Now,
};
db.Insert(valuation); // Insert the object in the database
// Objects created, let's stablish the relationship
euro.Valuations = new List<Valuation> { valuation };
db.UpdateWithChildren(euro); // Update the changes into the database
if (valuation.Stock == euro)
{
Debug.WriteLine("Inverse relationship already set, yay!");
}
// Get the object and the relationships
var storedValuation = db.GetWithChildren<Valuation>(valuation.Id);
if (euro.Symbol.Equals(storedValuation.Stock.Symbol))
{
Debug.WriteLine("Object and relationships loaded correctly!");
}
}
}
}
最佳答案
SQLite-Net 扩展现已作为适用于 MvvmCross 和 SQLite-Net 标准 PCL 风格的 NuGet 包提供。这应该可以解决此类问题,即库是使用一个 SQLite-Net 版本编译但使用另一个版本执行的,这可能会导致您所描述的问题。
链接:
- 对于 SQLite-Net PCL:https://www.nuget.org/packages/SQLiteNetExtensions/
- 对于 MvvmCross SQLite 社区插件:https://www.nuget.org/packages/SQLiteNetExtensions-MvvmCross/
关于Xamarin 表单上的 SQLite-Net 扩展示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24665304/