有没有办法将来自 2 个表的(JOIN)数据与 SQLite 结合在一起?
Is there a way to combine (JOIN) data from 2 tables together with SQLite?
我尝试了一些方法来合并 2 个 table,但结果 returns 只有第一个 table 的数据。
这是我的 tables:
[Table("Person")]
public class Person
{
[PrimaryKey, AutoIncrement]
public int PersonID { get; set; }
public string Name { get; set; }
public int CompanyID { get; set; }
}
[Table("Company")]
public class Company
{
[PrimaryKey, AutoIncrement]
public int CompanyID { get; set; }
public string Name { get; set; }
}
这是我的查询:
var result = await _Connection.QueryAsync<Person>("SELECT * FROM Person JOIN Company ON Person.CompanyID = Company.CompanyID");
return result;
但它只给出了第一个 table "Person" 的属性。我忘了什么?
你忘了用现在时 ;)
但实际上这 - _Connection.QueryAsync<Person>
将 return 只有 Person 字段,因为您将具体的 Person 类型指定为泛型。
创建第三个 class,它同时具有 Person 和 Company 字段或使用匿名类型,然后使用如下内容:
var query = from person in await db.Table<Person>().ToListAsync()
join company in await db.Table<Company>().ToListAsync()
on person.CompanyID = company.CompanyID
select new
{
Name = person.Name,
CompanyName = company.Name
// And so on
}
注意:由于 ToListAsync()
,这会将所有记录加载到内存中
更新:
您可以将 select
更改为:
而不是匿名类型
PersonCompany personCompany = from person in .....
//---cut
on person.CompanyID = company.CompanyID
select new PersonCompany
{
Name = person.Name,
CompanyName = company.Name
// And so on
}
我尝试了一些方法来合并 2 个 table,但结果 returns 只有第一个 table 的数据。
这是我的 tables:
[Table("Person")]
public class Person
{
[PrimaryKey, AutoIncrement]
public int PersonID { get; set; }
public string Name { get; set; }
public int CompanyID { get; set; }
}
[Table("Company")]
public class Company
{
[PrimaryKey, AutoIncrement]
public int CompanyID { get; set; }
public string Name { get; set; }
}
这是我的查询:
var result = await _Connection.QueryAsync<Person>("SELECT * FROM Person JOIN Company ON Person.CompanyID = Company.CompanyID");
return result;
但它只给出了第一个 table "Person" 的属性。我忘了什么?
你忘了用现在时 ;)
但实际上这 - _Connection.QueryAsync<Person>
将 return 只有 Person 字段,因为您将具体的 Person 类型指定为泛型。
创建第三个 class,它同时具有 Person 和 Company 字段或使用匿名类型,然后使用如下内容:
var query = from person in await db.Table<Person>().ToListAsync()
join company in await db.Table<Company>().ToListAsync()
on person.CompanyID = company.CompanyID
select new
{
Name = person.Name,
CompanyName = company.Name
// And so on
}
注意:由于 ToListAsync()
,这会将所有记录加载到内存中更新:
您可以将 select
更改为:
PersonCompany personCompany = from person in .....
//---cut
on person.CompanyID = company.CompanyID
select new PersonCompany
{
Name = person.Name,
CompanyName = company.Name
// And so on
}