SQLite-Net扩展:在主/明细方案中删除明细记录

时间:2018-11-06 00:08:59

标签: sqlite-net

删除Dentail记录的正确方法是什么?

我与估值实体(详细信息)在OneToMany关系中具有股票实体(主)。

我检索一个具有相关评估价值的股票实体。然后,从“评估”列表中删除一个实体,并调用UpdateWithChildrenAsync。

此更新的结果是,在删除的评估中外键为NULL,而不是我希望将此记录从物理上删除。

namespace TestSQLitePCL
{
    public class Stock
    {
        [PrimaryKey, AutoIncrement]
        public int? Id { get; set; }
        public string Symbol { get; set; }

        [OneToMany(CascadeOperations = CascadeOperation.All)]
        public List<Valuation> Valuations { get; set; }
    }
}

namespace TestSQLitePCL
{
    public class Valuation
    {
        [PrimaryKey, AutoIncrement]
        public int? Id { get; set; }
        [ForeignKey(typeof(Stock))]
        public int StockId { get; set; }
        public DateTime Time { get; set; }
        public decimal Price { get; set; }
    }
}



...
stock.Valuations.RemoveAt(0);
...
await _connection.UpdateWithChildrenAsync(stock);

1 个答案:

答案 0 :(得分:0)

从关系中删除元素不应从数据库中删除该对象。

从关系中删除它们时,可以手动将其删除(确保没有其他人引用该记录):

// Remove valuation from stock list
stock.Valuations.Remove(valuation);
await valuation.DeleteAsync();

或定期删除孤立对象以保持数据库干净。

// Delete orphaned valuations
conn.Execute("DELETE FROM Valuation WHERE stock_id = 0");