2016-11-21 44 views
4

我有以下配置。我有一個用戶。用戶有一個郵政地址和一個物理地址(見下文)。流利的api級聯刪除關係到一張表

public class UserProfile 
{ 
    public Guid UserProfileId {get; set;} 

    public Guid PostalAddressId {get;set;} 
    public virtual Address PostalAddress {get;set;} 

    public Guid PhysicalAddressId {get;set;} 
    public virtual Address PhysicalAddress {get;set;} 
} 

public class Address{ 
    public Guid AddressId {get;set;} 
    public string LineOne {get;set;} 
    public string LineTwo {get;set;} 
    public string LineThree {get;set;} 
} 

接下來是我流利的映射

public UserProfileMapping() 
{ 
    ToTable("UserProfile"); 
    HasKey(pk => pk.UserProfileId); 
    Property(pr => pr.UserProfileId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); 

    HasRequired(a => a.PostalAddress).WithMany().HasForeignKey(fk => fk.PostalAddressId); 
    HasRequired(a => a.PhysicalAddress).WithMany().HasForeignKey(fk => fk.PhysicalAddressId); 
} 

public AddressMapping() 
{ 
    ToTable("Address"); 
    HasKey(pk => pk.AddressId); 
    Property(pr => pr.AddressId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); 
} 

當我嘗試運行更新的數據庫,我得到:

引進國外KEY約束 'FK_dbo.UserProfile_dbo.Address_PhysicalAddressId' 上表 'UserProfile'可能會導致循環或多個級聯路徑。指定ON 刪除無操作或ON UPDATE NO ACTION,或修改其他FOREIGN KEY 約束。

我需要在Address對象上沒有任何反向映射。 我還需要能夠硬刪除UserProfile對象,包括其子地址(其中只有兩個地址表中的地址)。

我的問題是,我想要什麼?如果是這樣,我做錯了什麼?

[編輯] Address對象也用於對象,如UserCompany和Customer。

回答

0

由於地址不是用戶配置的孩子,但只是聯想,你不希望使用級聯刪除:

HasRequired(a => a.PostalAdress) 
    .WithMany() 
    .HasForeignKey(fk => fk.PostalAddressId) 
    .WillCascadeDelete(false); 
+0

對不起,我沒有提供足夠的信息。 Address對象可以不僅僅屬於UserProfile。一個公司對象也可以有一個地址,一個客戶也可以有一個地址。從我的理解,這將無法使用您的建議答案,因爲一對一的映射。我可以更新我的問題來反映這一點。 –

+0

如果可以將地址鏈接到其他對象,如何刪除userProfile及其子地址? – Kinetic

+0

如果地址不屬於UserProfile,則不希望級聯刪除。 – Kinetic