繁体   English   中英

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

[英]Entity Framework Core incorrectly querying relationships

我有一个使用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语句中取出了一堆字段):

从[AspNetRoles] AS中选择​​[p.AspNetUserRoles.User]。[Id],[p.AspNetUserRoles.User]。[UserName]内连接[p]。[Id]内加入[AspNetUserRoles] AS [p.AspNetUserRoles] AS。 ] = [p.AspNetUserRoles]。[角色ID]左联接[AspNetUsers] AS [p.AspNetUserRoles.User]打开[p.AspNetUserRoles]。[UserId1] = [p.AspNetUserRoles.User]。[Id]在[p] 。[名称] = @__ role_0

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

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

除了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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM