ORMLIte [ServiceStack]。 SaveReference方法不会在List中添加项目

时间:2014-12-17 18:10:54

标签: c# orm servicestack ormlite-servicestack

我有以下代码用于我的ORMLite演示:

[Alias("ProUser")]
public class DomainUser : IProUser
{
    public int UserType { get; set; }
    public string Id{ get; set; }

    [Reference]
    public Address HomeAddress { get; set; }

    [Reference]
    public List<Order> Orders { get; set; }

    [Ignore]
    public UserType UserTypeEnum
    {
        get { return (UserType)UserType; }
        set { UserType = (int)value; }
    }
}

public class Order
{
    [AutoIncrement]
    public int Id { get; set; }

    public string ProUserId { get; set; }

    public string Details { get; set; }

}
  1. 现在,您可以注意到DomainUser和Order with List Orders属性之间存在参照关系。
  2. 我可以调用Db.SaveReferences(user,user.Orders),看看如果我更改了域内的任何内容,那么它的效果非常好。
  3. 但是,如果我在列表中添加新项目,ORMLite不会保存此项。
  4. 我的测试下面很好地展示了这个探测器

    DomainUser user = repository.Find("Someone.Else") as DomainUser;
    user.UserTypeEnum = UserType.Domain;
    user.HomeAddress.StreetName = "Some new street";
    user.Orders[1].Details = "Nestle Chocolates";
    user.Orders.Add(new Order
    {
        Details = "Reese",
        ProUserId = user.Id
    });
    
    // This one would be OK since the user already has two orders in the DB
    Assert.AreEqual(2, user.Orders.Count);  
    repository.Update(user);
    
    
    DomainUser retval =  repository.Find(user.Id) as DomainUser;
    
    // However, this one would fail because no new order has been added.
    Assert.AreEqual(3, user.Orders.Count); 
    

    令人困惑的是,我看到ORMLite正在尝试添加新记录,因为我看到正在执行插入查询。我不确定DB为什么不反映它......

    以下是Repository在Find()和Update()方法中的样子:

    public IProUser Find(string id)
            {
                DomainUser user = Db.LoadSingleById<DomainUser>(id);
                return user;
            }
    
     public IProUser Update(DomainUser user)
            {
                using(Db.OpenTransaction(IsolationLevel.ReadCommitted))
                { 
                    Db.Save(user);
                    Db.SaveReferences(user,user.HomeAddress);
                    Db.SaveReferences(user,user.Orders);
    
                    return Find(user.Id);
                }
            }
    

1 个答案:

答案 0 :(得分:1)

您需要显式提交ADO.NET事务,即:

using(var trans = Db.OpenTransaction(IsolationLevel.ReadCommitted))
{ 
    Db.Save(user);
    Db.SaveReferences(user,user.HomeAddress);
    Db.SaveReferences(user,user.Orders);

    trans.Commit();

    return Find(user.Id);
}