2017-08-08 90 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

这是更好编辑你的问题,以便它真正表达你的问题的基础。 “我的根本问题”,为什么有隐秘的基础问题?为什么不把它们写在你的问题上呢。为什么说你有一对多,而实际上你的问题是你有一个有两个引用另一个表的类?如果您提出问题,请尝试通过编写适当的要求来帮助答复者,而不是让他们猜测。 –