类别:
class Track
{
...
public virtual IDictionary<People, Role> PeopleRoles { get; set; }
}
映射:
<class name="Track" ...>
...
<map name="PeopleRoles" table="track_people_role">
<key column="track_id"/>
<map-key-many-to-many column="people_id" class="People"/>
<many-to-many column="role_id" class="Role"/>
</map>
</class>
当我执行下面的代码时,我可以看到在track_people_role表中插入的行为47637,10,1
Person p = PersonManager.GetById(10);
Role pr = RoleManager.GetById(1);
Track t = TrackManager.GetById(47637);
t.PeopleRoles.Add(p, pr);
TrackManager.Save(t);
当我以不同的角色执行上一个后,我得到“已经添加了具有相同键的项目”错误
Person p = PersonManager.GetById(10);
Role pr = RoleManager.GetById(2);
Track t = TrackManager.GetById(47637);
t.PeopleRoles.Add(p, pr);
TrackManager.Save(t);
我可以设法插入第二行的任何想法。
编辑:
映射:
<class name="TrackPersonRole, App.Data" table="trackpeoplerole" lazy="true">
<composite-id>
<key-many-to-one name="Person" class="Person" column="people_id"/>
<key-many-to-one name="Role" class="Role" column="role_id"/>
</composite-id>
</class>
<class name="Track" ...>
...
<bag name="TrackPeopleRoles">
<key column="track_id"/>
<one-to-many class="TrackPersonRole"/>
</bag>
</class>
TrackPersonRole tpr = new TrackPersonRole();
tpr.Person = PersonManager.GetById(10);
tpr.Role = RoleManager.GetById(2);
entity.PeopleRoles.Add(tpr);
TrackManager.SaveOrUpdate(entity);
生成以下更新语句,而不是插入。
UPDATE trackpeoplerole SET track_id = 47637 /* ?p0 */
WHERE people_id = 10 /* ?p1 */ AND role_id = 2 /* ?p2 */
答案 0 :(得分:0)
错误消息是正确的:您正在向字典中添加重复的密钥。
它甚至不是来自NHibernate - 它是由Dictionary
类生成的。
如果Track
可以在多个Person
中拥有相同的Role
,则您必须将track_person_role
表格映射为实体:
class Track
{
...
public virtual ICollection<TrackPersonRole> PeopleRoles { get; set; }
}
class TrackPeopleRole
{
public virtual Person Person { get; set; }
public virtual Role Role { get; set; }
}
映射:
<class name="Track" ...>
...
<bag name="TrackPeopleRoles">
<key column="track_id"/>
<one-to-many class="TrackPersonRole"/>
</map>
</class>
有关inverse
和cascade
的详细信息,但请从此开始。