1 回答

TA貢獻(xiàn)1841條經(jīng)驗(yàn) 獲得超3個(gè)贊
正如聊天中所討論的,我很少相信 EF 的多對(duì)多功能,更不用說(shuō) EF Core。這不是直接針對(duì)您的問(wèn)題,而是解釋了如果這是我的項(xiàng)目我將如何處理。
您已經(jīng)擁有ApplicationUser了,因此從它們中分離出來(lái)的表只會(huì)存在于定義不同ApplicationUsers. 每個(gè)用戶可以擁有多個(gè)所有內(nèi)容:關(guān)注者、關(guān)注者和阻止。用戶并不直接控制誰(shuí)跟隨他們,所以不需要自己的表。您可以通過(guò)查看關(guān)注者表來(lái)確定誰(shuí)關(guān)注了用戶。
public class ApplicationUser : IdentityUser
{
public virtual ICollection<UserFollow> Following { get; set; }
public virtual ICollection<UserFollow> Followers { get; set; }
public virtual ICollection<UserBlock> BlockedUsers { get; set; }
}
public class UserFollow
{
public int Id { get; set; }
[ForeignKey(nameof(SourceUserId))]
public ApplicationUser SourceUser { get; set; }
public string SourceUserId { get; set; }
[ForeignKey(nameof(FollowedUserId))]
public ApplicationUser FollowedUser { get; set; }
public string FollowedUserId { get; set; }
}
public class UserBlock
{
public int Id { get; set; }
[ForeignKey(nameof(SourceUserId))]
public ApplicationUser SourceUser { get; set; }
public string SourceUserId { get; set; }
[ForeignKey(nameof(BlockedUserId))]
public ApplicationUser BlockedUser { get; set; }
public string BlockedUserId { get; set; }
}
然后你的配置不會(huì)有太大變化(考慮這個(gè)偽,未經(jīng)測(cè)試):
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
moderlBuilder.Entity<UserFollow>()
.HasOne(l => l.SourceUser)
.WithMany(a => a.Following)
.HasForeignKey(l => l.SourceUserId);
moderlBuilder.Entity<UserFollow>()
.HasOne(l => l.FollowedUser)
.WithMany(a => a.Followers)
.HasForeignKey(l => l.FollowedUserId);
moderlBuilder.Entity<UserBlock>()
.HasOne(l => l.SourceUser)
.WithMany(a => a.BlockedUsers)
.HasForeignKey(l => l.SourceUserId);
}
(請(qǐng)注意,我總是使用一個(gè)簡(jiǎn)單的鍵(Id只是為了便于查詢),但您可以根據(jù)需要將其改回復(fù)合鍵)
- 1 回答
- 0 關(guān)注
- 196 瀏覽
添加回答
舉報(bào)