【发布时间】:2021-05-01 14:03:40
【问题描述】:
如何使用带有 Fluent API 的 EF Core 5 配置类似于 Twitter 关注和关注者类型的关系?我尝试了各种不同的配置方法,唯一能让它工作的方法是我忽略了用户实体上的导航属性。我目前正在将我的代码从 EF Core 2.1 迁移到 5。以下配置在早期工作。 (不知道是不是配置错误)
public class User
{
public long Id { get; set; }
public string Name { get; set; }
public ICollection<UserFollower> Followers { get; set; }
public ICollection<UserFollower> Following { get; set; }
}
public class UserFollower
{
public long UserId { get; set; }
public User User { get; set; }
public long FollowedById { get; set; }
public User FollowedBy { get; set; }
}
public class UserFollowerConfiguration : IEntityTypeConfiguration<UserFollower>
{
public void Configure(EntityTypeBuilder<UserFollower> builder)
{
builder.HasKey(p => new { p.UserId, p.FollowedById });
builder.HasOne(p => p.User)
.WithMany(i => i.Followers)
.HasForeignKey(i => i.UserId);
builder.HasOne(p => p.FollowedBy)
.WithMany(i => i.Following)
.HasForeignKey(i => i.FollowedById);
}
}
此配置在保存到数据库时会引发错误。
SqlException: Violation of PRIMARY KEY constraint 'PK_UserFollower'.
Cannot insert duplicate key in object 'dbo.UserFollower'. The duplicate key value is (111, 111).
即使尝试直接添加到 DbContext 并在其上调用 SaveChanges()。
Context.Add(new UserFollower() {UserId = 222, FollowedById = 111});
将这种关系映射到 EF Core 5 的推荐方法是什么?请注意,我确实需要访问 UserFollowers 表,而无需通过用户的导航属性。
编辑#1
以下是 DbContext 的OnModelCreating()
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ApplyConfigurations(typeof(DbContext).Assembly);
/*few configurations unrelated to UserFollower entity*/
}
用户实体有如下配置,
builder.HasKey(i => i.Id);
builder.Property(i => i.Id).ValueGeneratedOnAdd();
【问题讨论】:
-
配置没问题。显然您在应用(不确定是什么)更改时做错了 - 您最好显示该代码。
-
代码完全没问题。似乎问题出在其他地方。
-
@IvanStoev 我已经用配置应用代码更新了问题。
标签: c# entity-framework-core ef-code-first ef-fluent-api ef-core-5.0