使用Where子句返回子项

时间:2014-09-15 13:52:09

标签: c# sqlite sqlite-net sqlite-net-extensions

我在我的Xamarin项目中使用SQL-NET Extensions。我试图使用where子句返回我的模型的儿童的emelments。使用网站上的示例模型:

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参数为null。然后我可以循环遍历每个结果并设置它们,但我认为在原始查询中必须有更好的方法来执行它?

1 个答案:

答案 0 :(得分:2)

您可以获取调用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。对于像这样的简单查询,它应该按预期工作。