【发布时间】:2014-08-16 22:18:29
【问题描述】:
我创建了三个实体:
public class Company : EntityBase
{
some properties
public virtual IList<UserCompanyAttachment> AttachedUsers {get; set;}
public virtual void AttachUser(User userToAttach)
{
var userCompanyAttachment = new UserCompanyAttachment()
{
AttachedCompany = this,
AttachedUser = userToAttach
}
AttachedUsers.Add(userCompanyAttachment);
}
}
public class User : EntityBase
{
some properties
public virtual IList<UserCompanyAttachment> AttachedCompanies {get; set;}
public virtual void AttachCompany(Company companyToAttach)
{
var userCompanyAttachment = new UserCompanyAttachment()
{
AttachedCompany = companyToAttach,
AttachedUser = this
}
AttachedCompanies.Add(userCompanyAttachment);
}
}
public class UserCompanyAttachment : EntityBase
{
public virtual User AttachedUser { get; set; }
public virtual Company AttachedCompany { get; set; }
.. some properties ..
}
我已经用 fluent 创建了关系 - 公司和用户映射得到:
HasMany(x => x.AttachedCompanies/Users).Inverse.Cascade.All();
UserCompanyAttachemnt 映射为:
References(x => x.AttachedUser);
References(x => x.AttachedCompany);
我之所以没有创建正常的多对多关系是因为我需要存储有关附件的信息。 (没有冗余,因为在这两种情况下,数据库中都存在物理上的第三个表)但是,当我尝试使用 companyObject.AttachUser(newUser) 附加用户时,更改仅在 company.AttachedUsers 上可见 - 但在 newUser.AttachedCompanies 中不可见。有没有办法通过一些映射来推动更改?为什么会失败?
编辑:添加了失败的单元测试
[Test]
public void CanCorrectlyMapUserCompanyAttachmentWhenAddedByUser()
{
var testUser = new User() { PasswordHash = "pp", PasswordSalt = "qq", Username = "user" };
var testCompany = new Company()
{
Address = new Address() { City = "q" },
AgentName = "tt",
Comments = "z",
CompanyName = "g",
MailAddress = "@@",
NIP = 231123
};
DbSession.Save(testUser);
DbSession.Save(testCompany);
testUser.AttachCompany(testCompany);
DbSession.Flush();
var addedAttachment = DbSession.Get<UserCompanyAttachment>(1);
User addedUser = DbSession.Get<User>(1);
Company addedCompany = DbSession.Get<Company>(1);
Assert.AreEqual(addedAttachment .AttachedUser.Id, 1);
Assert.AreEqual(addedAttachment .AttachedCompany.Id, 1);
Assert.IsTrue(addedUser.AttachedCompanies.Contains(addedAttachment));
Assert.IsTrue(addedCompany.AttachedUsers.Contains(addedAttachment)); // here it fails
}
【问题讨论】:
标签: c# nhibernate fluent-nhibernate