2 回答
TA贡献1820条经验 获得超10个赞
您是否尝试向用户类添加关系列表,即
public class User : IdentityUser {
List<Relationship> Relationships {get;set;}
}
这可能有助于 EF 充分理解这种关系。
TA贡献1853条经验 获得超18个赞
看起来您正在尝试many-to-many使用相同的实体进行配置。为此,请编写您的User和Relationship模型类,如下所示:
public class User : IdentityUser
{
public List<Relationship> UserFriends { get; set; }
public List<Relationship> FriendUsers { get; set; }
}
public class Relationship {
public string UserId {get; set;} // `UserId` type is string as you are using default identity
public User User {get;set;}
public string FriendId {get; set;}
public User Friend {get;set;}
// Enum of Status (Approved, Pending, Denied, Blocked)
public RelationshipStatus RelationshipStatus {get;set;}
public DateTime RelationshipCreationDate {get;set;}
}
然后在模型构建器实体配置中:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Relationship>().HasKey(r => new {r.UserId, r.FriendId});
modelBuilder.Entity<Relationship>()
.HasOne(r => r.User)
.WithMany(u => u.UserFriends)
.HasForeignKey(r => r.UserId).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Relationship>()
.HasOne(r => r.Friend)
.WithMany(f => f.FriendUsers)
.HasForeignKey(r => r.FriendId).OnDelete(DeleteBehavior.Restrict);
}
现在它应该可以正常工作了!
- 2 回答
- 0 关注
- 145 浏览
添加回答
举报