ORMLIte[ServiceStack] .保存引用方法不会在列表中添加项
本文关键字:列表 添加 方法 ServiceStack 保存 引用 ORMLIte | 更新日期: 2023-09-27 18:34:27
我有以下代码,我正在为我的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; }
}
- 现在,正如您注意到的那样,"域用户"和"具有列表订单的订单"属性之间存在引用关系。
- 我可以调用 Db.SaveReferences(user, user.订单(,看看如果我更改了域内的任何东西,那么它运行良好。
- 但是,如果我在列表中添加新项目,ORMLite 不会保存它。
我下面的测试很好地证明了这个探头
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没有反映它....
以下是 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);
}
}
您需要显式提交 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);
}