实体框架核心错误地查询关系

时间:2018-08-12 04:35:17

标签: c# asp.net entity-framework asp.net-core

我有一个使用Identity 2.0的现有ASP.NET MVC应用程序。我正在尝试使用带有Ef Core 2.1的新Core 2.1应用程序查询用户对象。

我直接查询而不是使用UserManager / RoleManager,因为.NET MVC和.NET核心应用程序具有不同的版本,并且我不想让自己陷入困境。

我的问题是我无法让所有用户都具有特定角色。

我正在尝试在我的.net核心应用程序中这样做:

public partial class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
    : base(options)
    { }

    public virtual DbSet<ApplicationUser> AspNetUsers { get; set; }
    public virtual DbSet<AspNetRole> AspNetRoles { get; set; }
    public virtual DbSet<AspNetUserRole> AspNetUserRoles { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<AspNetUserRole>()
                        .HasKey(pc => new { pc.UserId, pc.RoleId });

    }
}

我的角色映射模型:

public class AspNetRole
{
    [Key]
    public Guid Id { get; set; }

    [MaxLength(256)]
    [Required]
    public string Name {get; set;}

    public virtual ICollection<AspNetUserRole> AspNetUserRoles {get; set;}

}

我的模型来映射用户:

 public class ApplicationUser : IdentityUser
{

    public virtual ICollection<AspNetUserRole> AspNetUserRoles {get; set;}

}

和我的联接表:

public class AspNetUserRole
{

    [MaxLength(256)]
    [Required]
    public Guid UserId { get; set; }

    public ApplicationUser User {get; set;}

    [MaxLength(256)]
    [Required]
    public Guid RoleId { get; set; }

    public AspNetRole Role {get; set;} 

}

我在存储库中运行的查询是:

    var usersInRole = _context.AspNetRoles
        .Where(p => p.Name == "Manager")
        .SelectMany(p => p.AspNetUserRoles)
        .Select(pc => pc.User);

但是查询失败。 EF的翻译如下(我从SELECT语句中取出了一堆字段):

选择[p.AspNetUserRoles.User]。[Id],[p.AspNetUserRoles.User]。[UserName] 从[AspNetRoles] AS [p] 内联接[AspNetUserRoles] AS [p.AspNetUserRoles]开启[p]。[Id] = [p.AspNetUserRoles]。[RoleId] 左联接[AspNetUsers] AS [p.AspNetUserRoles.User]开启[p.AspNetUserRoles]。[UserId1] = [p.AspNetUserRoles.User]。[Id] 在[p]。[名称] = @__ role_0

如您所见,它错误地查询了[p.AspNetUserRoles]。[UserId1],因此出现以下错误:

System.Data.SqlClient.SqlException(0x80131904):无效的列名'UserId1'。

1 个答案:

答案 0 :(得分:2)

除了ApplicationDbContext类的OnModelCreating方法中的代码外,您还需要添加以下代码

modelBuilder.Entity<AspNetUserRole>()
    .HasOne(aur => aur.User)
    .WithMany(aur => aur.AspNetUserRoles)
    .HasForeignKey(aur => aur.UserId);

modelBuilder.Entity<AspNetUserRole>()
    .HasOne(aur => aur.Role)
    .WithMany(aur => aur.AspNetUserRoles)
    .HasForeignKey(aur => aur.RoleId);
相关问题