UpdateWithChildren 不更新列表(OneToMany)关系

UpdateWithChildren not updating Lists (OneToMany) relationships

下面是一些重现问题的示例代码:

客户class

public class Customer
{
    private int _id;

    [Column("_id"), PrimaryKey, AutoIncrement]
    public int Id
    {
        get { return _id; }
        set
        {
            if (value != _id)
            {_id = value;}
        }
    }

   private string _name;

   [Column("_name")]
   public string Name
   {
       get { return _name; }
       set
       {
           if (value != _name)
           {_name = value;}
       }
   }

   private List<Order> _orders;
   [OneToMany(CascadeOperations = CascadeOperation.CascadeInsert | CascadeOperation.CascadeRead | CascadeOperation.CascadeDelete)]
   public List<Order> Orders
   {
       get { return _orders; }
       set
       {
           if (_orders != value)
           {
               _orders = value;
           }
       }
   } 

订单class

public class Order
{
    private int _id;

    [Column("_id"), PrimaryKey, AutoIncrement]
    public int Id
    {
        get { return _id; }
        set
        {
            if (value != _id)
                _id = value;
        }
    }

    private string _name;

    [Column("_name")]
    public string Name
    {
        get { return _name; }
        set
        {
            if (value != _name)
                _name = value;
        }
    }

    private int _customerId;

    [Column("_customerId"), ForeignKey(typeof(Customer))]
    public int CustomerId
    {
        get { return _customerId; }
        set
        {
            if (value != _customerId)
                _customerId = value;
        }
    }
}

数据库操作

Customer customer = new Customer(){Name = "Customer One"};
context.InsertWithChildren(customer, true);
customer.Orders = new List<Order>();
customer.Orders.Add(new Order(){Name="Sample order"});
context.UpdateWithChildren(customer);

// get a new copy from the db
var result = context.GetWithChildren<Customer>(customer.Id,true); 

List<Order> orders = result.Orders; // Orders.Count is 0

我是不是哪里做错了还是UpdateWithChildren应该这样工作?

编辑

看起来 UpdateWithChildren 不会插入新的 Order 如果数据库中不存在。首先插入订单,将其分配给客户,然后调用 UpdateWithChildren 建立关系。

Customer customer = new Customer(){Name = "Customer One"};
context.InsertWithChildren(customer, true);

List<Order> newOrders = new List<Order>();
newOrders.Add(new Order(){Name="Test order"});
context.InsertAllWithChildren(newOrders,true);

customer.Orders = newOrders;

context.UpdateWithChildren(customer);

var result = context.GetWithChildren<Customer>(customer.Id,true);

List<Order> orders = result.Orders; // Orders.Count is 1

我想这就是我应该做的?

正如您已经注意到的那样,UpdateWithChildren 不会将任何新对象插入到数据库中。它只是更新关系。如果要插入或更新对象,可以使用 InsertOrReplaceWithChildren 或先插入对象,然后更新关系。

或者您可以使用递归插入操作:

Customer customer = new Customer(){
    Name = "Customer One",
    Orders = new List<Order>{ new Order(){ Name="Test order" } }
};

// Recursively insert 'customer' and all its orders
context.InsertWithChildren(customer, true);