我不确定对象图的样子,但为什么不让会话弄清楚发生了什么变化?
void DoSomethingWithMembers()
{
// if session which loaded the members is not open anymore
foreach (var member in loggedInMembers.Select(loggedInMember => loggedInMember.Member))
{
session.Lock(member, LockMode.None); // reattach to session
}
// end if
// make changes to the (loggedIn)members
session.Flush(); // will persist any changes to a member
}
更新:作为对评论的回应,类似这样
public AuthenticationResult Authenticate(string username, string password)
{
if (loggedInUsers.ContainsKey(username))
return AuthenticationResult.AlreadyLoggedIn;
using (var session = OpenSession())
{
var member = session.Query<Member>().Where(m => m.Name == username).FirstOrDefault();
}
if (member == null)
return AuthenticationResult.NoUser;
if (member.Password != password)
return AuthenticationResult.WrongPassword;
loggedInUsers.Add(username, new LoggedInMember(DateTime.Now, member));
var dto = mapper.Map<Member, MemberDto>(member);
return new AuthenticationResult(dto);
}
public void Update(ICollection<MemberDto> dtos)
{
using (var session = OpenSession())
{
foreach (var dto in dtos)
{
Update(session, dto);
}
session.Flush();
}
}
void Update(ISession session, MemberDto dto)
{
LoggedInMember liMember;
if (!loggedInUsers.TryGetValue(dto.Name, out liMember)
throw new AuthException("not logged in")
session.Lock(li.Member, LockMode.None); // attach
mapper.Map<Member, MemberDto>(li.Member, dto);
}