问题描述
我有两个实体,用户和类,具有多对多关系。我正在使用.Net Core,并且在此博客文章HERE(直到第3部分)之后建立了关系。数据库可以工作,并且我能够添加类并填充联接表,但是我不知道如何检索用户已注册的所有类,或者以其他方式检索已注册特定用户的所有用户课。
我需要解决用户已经登录到类而不必在连接表中添加新条目的情况(这样仍然会引发错误)。
User.cs
public class User : IdentityUser
{
// Making the classes a JoinCollectionFacade allows us to perform actions like adding a class
public User()
=> Classes = new JoinCollectionFacade<Class,UserClass>(
UserClass,uc => uc.Class,c => new UserClass { User = this,Class = c });
public string FirstName { get; set; }
public string LastName { get; set; }
public string Type { get; set; }
//public string Email { get; set; }
public string Phone { get; set; }
public string Membership { get; set; }
private ICollection<UserClass> UserClass { get; } = new List<UserClass>();
// This element does not need to be mapped. It's used for easier reference
// to the Users enrolled in the class
[NotMapped]
public ICollection<Class> Classes { get; }
}
Class.cs
public class Class
{
// Making the classes a JoinCollectionFacade allows us to perform actions like adding a class
public Class()
=> Users = new JoinCollectionFacade<User,uc => uc.User,u => new Models.UserClass { User = u,Class = this });
public Class(Instructor i,string d)
{
Instructor = i;
Description = d;
}
public int Id { get; set; }
public virtual Instructor Instructor { get; set; } // Made virtual so we can take advantage of certain Entity Framework such as lazy loading (from Microsoft docs)
public string Description { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
private ICollection<UserClass> UserClass { get; } = new List<UserClass>();
// This element does not need to be mapped. It's used for easier reference
// to the Users enrolled in the class
[NotMapped]
public ICollection<User> Users { get; }
}
UserClass.cs
public class UserClass
{
public string UserId { get; set; }
public User User { get; set; }
public int ClassId { get; set; }
public Class Class { get; set; }
}
解决方法
我通过以下方式解决了我的问题
- 在User.cs和Class.cs中公开UserClass实例
- 在下面使用这种查询来检索所有注册特定班级的用户
var usersInClass = _context.Users
.Include(i => i.UserClass).ThenInclude(i => i.Class)
.Where(x => x.UserClass.Select(pc => pc.Class).Any(c => c.Id == id))
.ToList();