使用Where子句返回子项
本文关键字:返回 子句 Where 使用 | 更新日期: 2023-09-27 18:21:52
我在Xamarin项目中使用SQL-NET扩展。我正在尝试使用where子句返回我的模型的子级记忆。使用网站上的示例模型:
public class Stock
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(8)]
public string Symbol { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.All)] // 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; }
}
我可以成功地返回一个特定的项目,其中的孩子填充使用:
var storedValuation = db.GetWithChildren<Valuation>(valuation.Id);
但是,我不知道如何使用Where
子句来代替Get
。我试过:
var results = db.Table<Valuation>().Where(x=>x.Price > 5.0m).ToList();
返回时所有Stock参数均为空。然后我可以循环遍历每个结果并设置它们,但我认为在原始查询中一定有更好的方法可以做到这一点?
您可以获得任何调用GetChildren
方法的对象的关系:
var results = db.Table<Valuation>().Where(x=>x.Price > 5.0m).ToList();
foreach (var element in results) {
conn.GetChildren(element);
}
还有一种方便的方法可以查询名为GetAllWithChildren
的数据库,它以一种不那么冗长的方式执行相同的操作:
var results = conn.GetAllWithChildren<Valuation>(x => x.Price > 5.0m).ToList();
请考虑您无法访问此查询中的关系,因为它们需要未执行的JOIN
。对于像这样的简单查询,它应该按预期工作。