我有以下代码用于我的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; }
}
我的测试下面很好地展示了这个探测器
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);
}
}
答案 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);
}