代码之家  ›  专栏  ›  技术社区  ›  Evonet

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

  •  0
  • Evonet  · 技术社区  · 6 年前

    我有一个使用身份2的ASP.NET MVC应用程序。我正在尝试使用一个新的带有Ef Core 2.1的core2.1应用程序来查询用户对象。

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

    我正试图在.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);
    

    选择[p.AspNetUserRoles.User]。[Id],[p.AspNetUserRoles.User]。[UserName] 从[AspNetRoles]作为[p] 内部连接[AspNetUserRoles]作为[p].[Id]=[p.AspNetUserRoles].[RoleId]上的[p.AspNetUserRoles] 在[p.AspNetUserRoles].[UserId1]=[p.AspNetUserRoles.User].[Id]上将[AspNetUsers]作为[p.AspNetUserRoles.User]左键联接 其中[p].[Name]=@@角色

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

    1 回复  |  直到 6 年前
        1
  •  2
  •   Mohsin Mehmood    6 年前

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

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