2017-04-18 65 views
1

我遇到了与我的网站有关的问题。我有一个UserProfile类,在我的文件底部有两个导航属性,如下所示:第三次添加ICollection时,多对多关系删除连接表

public virtual ICollection<UserProfile> Followers { get; set; } 
public virtual ICollection<UserProfile> Following { get; set; } 

然后创建另一个表(我相信它被称为交叉表?),在这个表中它自己管理这个关系。这工作正常,我可以添加/从此列表中删除。我遇到麻烦的部分是当我想添加另一个名为“BlockedUsers”的导航属性时,所以它是这样的;

public virtual ICollection<UserProfile> Followers { get; set; } 
public virtual ICollection<UserProfile> Following { get; set; } 
public virtual ICollection<UserProfile> BlockedUsers { get; set; } 

当我运行添加迁移和更新的数据库,它会删除它之前创建我的关注/追随者名单表,并因此打破我的网站功能,我无法添加/从以下/删除关注名单。

为什么它这样做,我该如何解决它?

感谢,

欧文

+1

您是先使用Coding?如果是,请向我们展示您的实体映射! – Fals

+0

是的,我使用Code First,但是我没有添加任何自定义实体映射。我只是在我的模型中设置了一切。 – Owen

回答

0

我已经成功地工作了这一点使用FluentAPI。我以前没有真正考虑过它,但是我意识到这是实现我想要做的事情的唯一方法。

如果您采用第一个导航属性块(Follow/Follower),将创建一个相交表。但是,如果我添加第三个导航属性来执行相同的操作,它将删除此表。

为了同时拥有BlockedUsers和Following/Followers两个表,我必须使用FluentAPI手动创建这个相交。

这是我加入到我的IdentityModel.cs -

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     // Sets up Many-To-Many relationship for Following/Followers UserProfiles 
     modelBuilder.Entity<UserProfile>() 
     .HasMany(t => t.Followers) 
     .WithMany(t => t.Following); 

     // Sets up Many-To-Many relationship for Blocked UserProfiles 
     modelBuilder.Entity<UserProfile>() 
     .HasMany(t => t.BlockedUsers) 
     .WithMany(); 

     base.OnModelCreating(modelBuilder); 
    } 

我希望这可以帮助别人有同样的问题。

但是我仍然想知道为什么在添加任何FluentAPI代码之前,它首先删除了表。