我有以下类关系: SiteSettings包含一个包含EmailAddress
集合的组件public class SiteSettings
{
public virtual Guid Id { get; set; }
public virtual SiteComponent SiteComponent { get; set; }
}
public class SiteComponent
{
public virtual string Name { get; set; }
public virtual IList<EmailAddress> EmailAddresses { get; set; }
}
public class EmailAddress
{
public virtual Guid Id { get; set; }
public virtual string ToAddress { get; set; }
}
我按如下方式映射这些类(使用Fluent NHibernate):
.Override<SiteComponent>(obj => obj.HasMany(x => x.EmailAddresses).Cascade.AllDeleteOrphan())
我的存储库实现如下:
public void SetSiteSettings(SiteComponent newComponent)
{
SiteSettings dbSiteSetting = GetDbSiteSettings();
dbSiteSetting.SiteComponent = newComponent;
Merge(dbSiteSetting);
}
我运行以下测试:
public void Test()
{
SiteSettings siteSettings = new SiteSettings();
siteSettings.SiteComponent = new SiteComponent();
siteSettings.SiteComponent.Name = "Site-1";
siteSettings.SiteComponent.EmailAddresses.Add(new EmailAddresses ("foo@xxx.com"));
siteSettings.SiteComponent.EmailAddresses.Add(new EmailAddresses ("bar@xxx.com"));
using (var uow = UnitOfWorkManager.CreateUnitOfWork())
{
m_siteControllerRepository.SetSiteSettings(siteSettings);
uow.Commit();
}
siteSettings.SiteComponent.EmailAddresses.Add(new EmailToAddress("zoo@xxx.com"));
using (var uow = UnitOfWorkManager.CreateUnitOfWork())
{
m_siteControllerRepository.SetSiteSettings(siteSettings);
uow.Commit();
}
}
测试结果确定:
添加到EmailAddress类后,方法等于如下,测试失败:
public class EmailAddress
{
public virtual Guid Id { get; set; }
public virtual string ToAddress { get; set; }
public virtual bool Equals(EmailAddress other)
{
if (other == null)
{
return false;
}
return (ToAddress.Equals(other.ToAddress));
}
}
测试结果: 第一次更新后 - 将foo和bar电子邮件正确插入到EmailAddresses表中,并引用FK到SiteSettings表。 第二次更新后 - 动物园电子邮件正确插入,参考FK到SiteSettings但是! 2封第一封电子邮件(来自第1次更新)FK为空。
有没有办法映射单向(一对多)并在其类实现的集合上使用Merge? (等于不比较NHibernate ID)
谢谢, 海姆。