UpdateWithChildren sqlite 网络扩展

UpdateWithChildren sqlite-net-extensions

我混淆了 UpdateWithChildren 和 InsertOrReplaceWithChildren。
我无法让它与 UpdateWithChildren 一起使用,但它可以与 InsertOrReplaceWithChildren 一起使用。
所以我删除了数据库,然后应用 InsertOrReplaceWithChildren,
但问题是 Id 是 AutoIncrement,Id 不断添加。
你能给我一些建议吗?
谢谢

public class WeekHistory {
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public DayOfWeek DayOfWeek { get; set; }
public int NoOfDays { get; set; }

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

public class DayHistory {
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public int Hour { get; set; }
public Action Action { get; set; }
public TimeSpan Duration { get; set; }

[ForeignKey(typeof(WeekHistory))]     
public int WeekId { get; set; }
[ManyToOne]      // Many to one relationship with WeekHistory
public WeekHistory WeekHistory { get; set; }}


List<DayHistory> newMonday = new List<DayHistory>()
{
    new DayHistory() {Hour = 1, Action = Action.Known, Duration = new TimeSpan(0,20,0)},
    new DayHistory() {Hour = 1, Action = Action.Unknown, Duration = new TimeSpan(0,40,0)},
    new DayHistory() {Hour = 2, Action = Action.Known, Duration = new TimeSpan(0,40,0)},
    new DayHistory() {Hour = 2, Action = Action.Unknown, Duration = new TimeSpan(0,20,0)},
    new DayHistory() {Hour = 3, Action = Action.Known, Duration = new TimeSpan(0,50,0)},
    new DayHistory() {Hour = 3, Action = Action.Unknown, Duration = new TimeSpan(0,10,0)}
};

var mondayHistory = dbConn.GetWithChildren<WeekHistory>(1, true);       

//delete the db, instead of the UpdateWithChildren
dbConn.DeleteAll(mondayHistory.DayHistories);       

mondayHistory.DayHistories = newMonday;
mondayHistory.NoOfDays += 1;

//it won't update the child
//dbConn.UpdateWithChildren(mondayHistory);

//apply new db with children
dbConn.InsertOrReplaceWithChildren(mondayHistory);

我没有发现你的第二个样本有问题。您正在删除之前的 DayHistory 并插入新的,因此 ID 会有所不同,但无需担心。

关于你的第一个问题,UpdateWithChildren更新数据库中已经存在的寄存器。如果您在父对象上调用 UpdateWithChildren,子对象(在本例中为 DayHistory)将不会插入到数据库中。更新子项将不起作用,因为您没有分配任何主键,因此数据库也无法更新它们。

这里更简单的解决方案是先将元素插入数据库,然后调用 UpdateWithChildren 更新外键:

// Delete previous DayHistories to avoid orphaned objects
dbConn.DeleteAll(mondayHistory.DayHistories);

// Assign new elements
mondayHistory.DayHistories = newMonday;
// Insert new elements into database
dbConn.InsertAll(mondayHistory.DayHistories);
// Update parent object to correctly assign foreign keys for the relationships
dbConn.UpdateWithChildren(mondayHistory);