我有兩個表之間有多對多關係的映射。我如何從映射表中刪除一個條目,在我的情況下是'ProjectUser'?NHibernate - 如何從多對多關係中刪除項目?
public ProjectMap()
{
Id(x => x.Id);
Map(x => x.ProjectName);
Map(x => x.Description);
References<User>(x => x.Owner);
HasManyToMany(x => x.Users)
.Cascade.SaveUpdate()
.Table("ProjectUser")
.Not.LazyLoad();
}
public UserMap()
{
Id(x => x.Id);
Map(x => x.FirstName);
Map(x => x.LastName);
Map(x => x.UserName);
HasManyToMany(x => x.Projects)
.Cascade.SaveUpdate()
.Inverse()
.Table("ProjectUser")
.Not.LazyLoad();
}
編輯:按照答案中的建議將級聯更改爲SaveUpdate。這裏是我用來提交數據到SQLite數據庫的代碼。
using (var trans = session.BeginTransaction())
{
var existingUsers = project.Users.ToList();
foreach (var item in existingUsers)
{
if (selectedUsers.Count(x => x.Id == item.Id) == 0)
project.Users.RemoveAt(project.Users.IndexOf(item));
}
session.SaveOrUpdate(project); // This fixed the issue
session.Flush();
foreach (var item in selectedUsers)
{
if (project.Users.Count(x => x.Id == item.Id) == 0)
{
project.AddUser(session.Get<User>(item.Id));
}
}
session.SaveOrUpdate(project);
session.Flush();
trans.Commit();
}
// Add user code in Project class
public virtual void AddUser(User userToAdd)
{
if (this.Users == null)
this.Users = new List<User>();
userToAdd.Projects.Add(this);
this.Users.Add(userToAdd);
}
每當我嘗試保存/更新,我發現了以下錯誤:
a different object with the same identifier value was already associated with the session: 10, of entity: Models.Project
EDIT2:應該用session.SaveOrUpdate(項目),並調用Session.flush(),以避免上述錯誤。
這個固定的問題,我必須做一些額外的是保存和刷新之前,我刪除和添加其他projectUser。 – Raj 2012-02-16 21:31:24