简体   繁体   English

使用Where子句返回孩子

[英]Return children using a Where clause

I'm using the SQL-NET Extensions in my Xamarin project. 我在Xamarin项目中使用SQL-NET扩展 I am trying to return children emelments of my model using a where clause. 我正在尝试使用where子句返回模型的子项。 Using the example models on the website: 使用网站上的示例模型:

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; }
}

I can succesfully return a specific item with the children populated using: 我可以成功返回一个特定的项目,并使用以下子项填充孩子:

var storedValuation = db.GetWithChildren<Valuation>(valuation.Id);

However I can't work out how to do it using a Where clause instead of Get . 但是我不知道如何使用Where子句而不是Get来做到这一点。 I have tried: 我努力了:

var results = db.Table<Valuation>().Where(x=>x.Price > 5.0m).ToList();

This returns with all the Stock parameters being null. 这将返回所有Stock参数为null的情况。 I could then loop through each result and set them, but I assume there must be a better way to do it in the original query? 然后,我可以遍历每个结果并进行设置,但是我想必须在原始查询中有更好的方法吗?

You can obtain the relationships for any object calling GetChildren method: 您可以获取任何调用GetChildren方法的对象的关系:

var results = db.Table<Valuation>().Where(x=>x.Price > 5.0m).ToList();
foreach (var element in results) {
    conn.GetChildren(element);
}

There's also a convenience method for querying the database called GetAllWithChildren that performs the same operation in a less verbose way: 还有一种方便的方法可查询名为GetAllWithChildren的数据库,该方法以不太冗长的方式执行相同的操作:

var results = conn.GetAllWithChildren<Valuation>(x => x.Price > 5.0m).ToList();

Please take into account that you cannot access relationships in this query as they would require a JOIN that is not being performed. 请考虑到您无法访问此查询中的关系,因为它们将需要不执行的JOIN For simple queries like this it should work as expected. 对于像这样的简单查询,它应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM