2017-08-08 51 views
-1

我有這種一對多關係,Profile - > Follower,我需要一種方式來表示Follower是一些Profile(用戶) 。我如何創建結構以便將追隨者指定爲特定的配置文件?我想我可以只是堅持在型材的ID,但我想有一個關鍵的回輪廓實體如何爲實體創建一個外鍵,當該實體與父實體相同時

這裏是「個人資料」和「追隨者」實體

這裏

suedo代碼

public class Profile { 
    public virtual ICollection<Follower> Followers { get; set; } // one to many 
} 

public class Follower { 
    [Key] 
    public int FollowerId { get; set; } 

    public int ProfileRefId { get; set; } 

    // one-to-many here 
    [ForeignKey("ProfileRefId")] 
    public virtual Profile Profile { get; set; } 

    public DateTime Created { get; set; } 


    // code that shows the follower is some specific profile/user 
    ???? 

} 

回答

0

你提到你在Profile和Follower之間有一對多的關係。

通常這意味着每個配置文件都有零個或多個關注者,並且每個關注者都屬於一個配置文件。換句話說:一個追隨者HAS一個配置文件,而不是IS一個配置文件。在軟件設計方面:一個追隨者使用組合來描述它與一個配置文件的關係。它不使用繼承。

原因是因爲如果您有一個配置文件P1擁有兩個關注者F1和F2,那麼這兩個關注者都會引用相同的P1。

其效果是,當更改追隨者F1的配置文件的任何屬性時,這些屬性也會在追隨者F2的配置文件中更改。這是預期的行爲,因爲F1的配置文件與F2的配置文件是相同的配置文件。

如果您要使用繼承來爲跟隨者的Profile部分建模,那麼與F1和F2相比,他們都將擁有自己的Profile。更改F1的配置文件屬性不會更改F2的配置文件屬性。

如果你真的想要後者,你的設計不是一對多的關係 。見後面如何實現繼承

Proper configuration of one-to-many relation:

class Profile 
{ 
    public int Id {get; set;} 

    // a Profile has zero or more followers: 
    public virtual ICollection<Follower> Followers {get; set;} 
    ... 
} 

class Follower 
{ 
    public int Id {get; set;} 

    // a follower belongs to exactly one Profile (via foreign key ProfileId) 
    public int ProfileId {get; set;} 
    public virtual Profile Profile {get; set;} 
    ... 
} 

的好處是,實體框架自動識別出這是一個一對多的關係。沒有屬性,也沒有流暢的API需要。此外:開發人員會立即看到你打算設計一對多的關係。

繼承在實體框架

如果您打算實現繼承,有幾個策略來做到這一點。我最經常使用的是Table-Per-Concrete-Class (TPC).

在TPC中,每個將實例化對象的類都會獲取它自己的表。該表具有該類的屬性以及基類的屬性。

這個設計是其他人最容易理解的,並且通過快速檢索和更新給出了最簡單的數據庫。對於每個要訪問的對象,只需要一個表。

除此之外,它完全模仿繼承的軟件行爲:如果創建Follower對象,則此對象自動具有Profile屬性。如果刪除跟隨者對象,則其配置文件屬性也會被刪除。更改追隨者的配置文件屬性之一,不會影響任何其他追隨者的配置文件屬性。

class Profile 
{ 
    ... // profile properties 
} 

// A Follower IS a Profile: 
class Follower : Profile 
{ 
    public int Id {get; set;} 
    ... // Follower properties 
} 

class MyDbContrext : DbContext 
{ 
    public DbSet<Follower> Followers{get; set;} 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     // tell that the Profile base class properties of Follower should be in the 
     // Followers table: 
     modelBuilder.Entity<Follower>().Map(m => 
     { 
      m.MapInheritedProperties(); 
      m.ToTable(nameof(MyDbContext.Followers)); 
     }); 
    } 
+0

我做了適當的更改以創建正確的一對多關係。但是我的根本問題實際上與創建具有兩個外鍵的'追隨者'表'返回到同一個表'配置文件'有關。其中一個將成爲父母,另一個將返回一些隨機檔案(追隨者)。我發現我在找什麼在這裏https://stackoverflow.com/questions/28570916/defining-multiple-foreign-key-for-the-same-table-in-entity-framework-code-first – user1186050

+0

這是更好編輯你的問題,以便它真正表達你的問題的基礎。 「我的根本問題」,爲什麼有隱祕的基礎問題?爲什麼不把它們寫在你的問題上呢。爲什麼說你有一對多,而實際上你的問題是你有一個有兩個引用另一個表的類?如果您提出問題,請嘗試通過編寫適當的要求來幫助答覆者,而不是讓他們猜測。 –

相關問題