2010-08-04 163 views
0

我在使用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類代表機構之間的多對多關係。

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 ()來保存公司實體。

任何想法,我在做什麼錯在這裏,由於這種行爲?

+0

你還可以發佈你的映射類嗎? – 2010-08-04 13:05:36

回答

0

可能您必須設置.Cascade.AllDeleteOrphan(); (cascade =「all-delete-orphan」)映射。

此外,如果您發佈的映射會更容易,因爲我使用自動映射爲您解答

1

我不得不overrid本組織的映射如下解決這個問題:

mapping.HasMany(C => c.RelatedOrganisations).Inverse()。ForeignKeyCascadeOnDelete()。表(「OrganisationRelationship」);