我知道我们可以进行多表查询,如下所示:
using (var db = new SQLiteConnection(new SQLitePlatformWinRT(), App.DB_PATH))
{
var result = db.Query<PersonWithAddress>(
@"SELECT Person.Id, Person.Name, Person.Surname,
Address.Street, Address.City, Address.Country
FROM Person INNER JOIN Address ON Person.AddressId = Address.Id;");
}
private class PersonWithAddress
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
*来自Query multiple tables SQLite Windows 10 UWP的参考
但是我需要结果类 PersonWithAddress 应该是:
private class PersonWithAddress
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public Address mAddress { get; set}
}
private class Address {
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
我正在寻找DataReader的方法,但看起来UWP上的SQLite不支持它。
答案 0 :(得分:3)
这是一个Portable Class Library for SQLite,提供类似于DataReader的方法。
要使用此库,我们可以从NuGet开始安装,然后使用它,如下所示:
List<PersonWithAddress> PersonWithAddressList = new List<PersonWithAddress>();
using (var connection = new SQLitePCL.SQLiteConnection(DB_PATH))
{
using (var statement = connection.Prepare(@"SELECT Person.Id, Person.Name, Person.Surname, Address.Street, Address.City, Address.Country FROM Person INNER JOIN Address ON Person.AddressId = Address.Id;"))
{
while (statement.Step() == SQLitePCL.SQLiteResult.ROW)
{
var personWithAddress = new PersonWithAddress();
personWithAddress.Id = Convert.ToInt32(statement[0]);
personWithAddress.Name = (string)statement[1];
personWithAddress.Surname = (string)statement[2];
personWithAddress.mAddress.Street = (string)statement[3];
personWithAddress.mAddress.City = (string)statement[4];
personWithAddress.mAddress.Country = (string)statement[5];
PersonWithAddressList.Add(personWithAddress);
}
}
}
有关详细信息,请参阅此博客:The new Portable Class Library for SQLite。
多表查询的另一种方法是使用SQLite-Net Extensions,您可以指定实体中的关系。例如,在您的项目中,添加对SQLiteNetExtensions NuGet package的引用。也可以在SQLiteNetExtensions.Async NuGet package中使用Async支持。然后改变你的课程如下:
public class Person
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[ForeignKey(typeof(Address))]
public int AddressId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
[ManyToOne]
public Address mAddress { get; set; }
}
public class Address
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<Person> Persons { get; set; }
}
在此之后,我们可以使用以下代码来获取所有具有地址的人:
using (var connection = new SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), DB_PATH))
{
List<Person> PersonsWithAddress = connection.GetAllWithChildren<Person>();
}