在EF Core 5中创建三方关系可以通过以下步骤实现:
以下是一个示例代码:
// User.cs
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Role> Roles { get; set; }
}
// Role.cs
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<User> Users { get; set; }
}
// UserRole.cs
public class UserRole
{
public int UserId { get; set; }
public User User { get; set; }
public int RoleId { get; set; }
public Role Role { get; set; }
}
// DbContext.cs
public class MyDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserRole>()
.HasKey(ur => new { ur.UserId, ur.RoleId });
modelBuilder.Entity<UserRole>()
.HasOne(ur => ur.User)
.WithMany(u => u.Roles)
.HasForeignKey(ur => ur.UserId);
modelBuilder.Entity<UserRole>()
.HasOne(ur => ur.Role)
.WithMany(r => r.Users)
.HasForeignKey(ur => ur.RoleId);
}
}
这样,就成功地在EF Core 5中创建了三方关系。在实际应用中,可以根据需要使用相关的查询和操作方法来处理三方关系的数据。
领取专属 10元无门槛券
手把手带您无忧上云