Fluent-Nhibernate多对多关系问题

时间:2010-08-04 08:21:37

标签: fluent-nhibernate

我在尝试使用Fluent Nhibernate删除多对多关系时遇到了问题。我有以下域类:

public class Organisation
{
   public virtual int Id {get; set;}

   private IList<OrganisationRelationshiop> relatedOrganisations; 

   public virtual IList<OrganisationRelationship> RelatedOrganisation
   {
       get
       {
           return this.relatedOrganisations;
       }

      protected set
      {
           this.relatedOrganisations = value;
      }
    }


    public virtual void RemoveRelatedOrganisation(OrganisationRelationship organisationRelationship)
    {
        this.relatedOrganisations.Remove(organisationRelationship);
    }

}

这是我的OrganisationRelationship类,它代表了orgnaisations之间的多对多关系。

   public class OrganisationRelationship 
   {
       public virtual int Id {get; set;}

       public virtual Organisation Organisation{ get; set; }

       public virtual OrganisationRelationshipType OrganisationRelationshipType { get; set; }

       public virtual Organisation RelatedOrganisation { get; set; }
   }

她是桌子的脚本:

组织表:

CREATE TABLE [dbo].[Organisation](
[Id] [int] IDENTITY(1,1) NOT NULL,
[OrganisationName] [nvarchar](200) NOT NULL,
CONSTRAINT [PK_Organisation] PRIMARY KEY CLUSTERED 
(
[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,    ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

OrganisationRelationshop表:

CREATE TABLE [dbo].[OrganisationRelationship](
[Id] [int] IDENTITY(1,1) NOT NULL,
[OrganisationId] [int] NOT NULL,
[RelatedOrganisationId] [int] NOT NULL,
[OrganisationRelationshipTypeId] [int] NOT NULL,
CONSTRAINT [PK_OrganisationRelationship] PRIMARY KEY CLUSTERED 
(
[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,        ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

OrganisationRelationType表:

CREATE TABLE [dbo].[OrganisationRelationshipType](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_OrganisationRelationshipType] PRIMARY KEY CLUSTERED 
(
[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,    ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

一切都按预期工作但当我尝试删除关系时,流畅的Nhibernate尝试将CompanyId设置为该特定记录的null,而不是从CompanyRelationship表中删除记录。以下是我在NHProf中可以看到的查询:

UPDATE CompanyRelationship
SET    CompanyId = null
WHERE  CompanyId = 3893 /* @p0 */
AND Id = 487 /* @p1 */

要删除记录,我调用RemoveRelatedCompany函数,该函数从relatedCompanies列表中删除特定的CompanyRelationship,然后调用Session.Save()和Session.Flush()来保存Company实体。

关于我在这里做错了什么想法由于这个行为?

2 个答案:

答案 0 :(得分:1)

当我使用AutoMapping时,我必须按照以下方式覆盖本组织的映射以解决此问题:

mapping.HasMany(c =&gt; c.RelatedOrganisations).Inverse()。ForeignKeyCascadeOnDelete()。Table(“OrganisationRelationship”);

答案 1 :(得分:0)

可能你必须设置.Cascade.AllDeleteOrphan(); (cascade =“all-delete-orphan”)在你的映射上。

另外,如果你发布你的映射会更容易回答你