c# – NHibernate – 如何从多对多关系中删除项目?
作者:互联网
我跟踪两个表之间的映射,它们之间具有多对多关系.如何从映射表中删除一个条目,在我的情况下是“ProjectUser”?
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();
}
编辑:按照答案中的建议将Cascade更改为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条目而不是实际删除另一侧的实体,则需要从Cascade.All()更改为Cascade.SaveUpdate().
目前,如果您从项目中删除了用户并保存了项目,则会删除ProjectUser条目和User对象.
标签:c,nhibernate,fluent-nhibernate,nhibernate-mapping,fluent-nhibernate-mapping 来源: https://codeday.me/bug/20190613/1234220.html