我想使用 MySQL 在 EF Core 中创建多对多关系,以便一个用户可以拥有多个角色,并且可以将角色分配给多个用户。我遵循了 Microsoft 的指南,但是当我运行
Users.SingleOrDefault()
时,结果的角色集合为空。
public class User
{
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
public string Password { get; set; }
[Required]
public ICollection<Role> Roles { get; set; }
}
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<User> Users { get; set; }
}
public class DatabaseService : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
private static string connectionString = "Server=localhost;Database=mydb;Uid=user;Pwd=mypwd;";
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithMany(u => u.Users)
.UsingEntity("UsersRoles");
}
}
在数据库中保存和查询数据
Collection<Role> roles = new()
{
new Role
{
Name = "Customer"
},
new Role
{
Name = "Administrator"
}
};
User newUser = new()
{
Email = register.Email,
Password = hashedPassword,
FirstName = register.FirstName,
LastName = register.LastName,
Roles = roles
};
database.Users.Add(newUser);
database.SaveChanges();
User? user = database.Users.SingleOrDefault(user => user.Email == login.Email && user.Password == HashPassword(login.Password));
Console.WriteLine(user.Roles); //null
尽管如此,数据库的连接表包含数据。
很抱歉,但我无法发表评论,这就是为什么我会发布答案:
尝试将用户设为虚拟,希望对您有帮助
`public virtual ICollection<User> Users { get; set; }