[英]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.