我尝试从已经找到的用户中加载朋友列表和朋友列表,并为每个消息列表加载。
不工作 仅加载好友,不加载每个好友中的邮件
_context.Entry(ldetails).Collection(p => p.ListFriends).Query()。 Include(r => r.MessagesDetails).Load();
我的数据结构
public class RegistrationUser
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PMId { get; set; }
[Required]
[Column(TypeName ="varchar(16)")]
public string UserName { get; set; }
[Required]
[Column(TypeName = "varchar(16)")]
public string Password { get; set; }
[Column(TypeName = "varchar(480)")]
public string Token { get; set; }
public ICollection<ListFriend> ListFriends { get; set; }
public RegistrationUser()
{
ListFriends = new List<ListFriend>();
}
}
public class ListFriend
{
[Key,Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Required]
[Column(TypeName ="varchar(16)")]
public string UserFriendName { get; set; }
public ICollection<MessagesDetail> MessagesDetails { get; set; }
public ListFriend()
{
MessagesDetails = new List<MessagesDetail>();
}
}
public class MessagesDetail
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key,Column(Order = 0)]
public int PMIdMes { get; set; }
[Required]
[Column(TypeName ="nvarchar(240)")]
public string TextMessage{ get; set; }
[Required]
[Column(TypeName = "varchar(16)")]
public string SenderUser { get; set; }
[Required]
[Column(TypeName = "varchar(16)")]
public string CatcherUser { get; set; }
}
我的方法不起作用
[HttpPost("EnterUserDetail")]
public async Task<ActionResult<RegistrationUser>> postUserDetail( RegistrationUser registrationUser )
{
var ldetails = _context.RegistrationUsers.SingleOrDefault(c=>c.UserName==registrationUser.UserName);
var pdetails = _context.RegistrationUsers.SingleOrDefault(c=>c.Password==registrationUser.Password);
if (ldetails == null && pdetails == null)
{
return NotFound();
}
//_context.Entry(ldetails).Collection("ListFriends").Load();
_context.Entry(ldetails).Collection(p=>p.ListFriends).Query().Include(r=>r.MessagesDetails).Load();
//_context.Entry(ldetails).Collection("ListFriends").IsLoaded = true;
//await _context.SaveChangesAsync();
return ldetails;
}
答案 0 :(得分:0)
您实际上正在向数据库发出3个请求,以获得所需的结果。一种更好的,优化的方法可以实现这一目标,例如
[HttpPost("EnterUserDetail")]
public async Task<ActionResult<RegistrationUser>> postUserDetail( RegistrationUser registrationUser)
{
// send one query to database to get the result and include here.
var ldetails = _context.RegistrationUsers.Include(i => i.ListFriends).SingleOrDefault(c => c.UserName == registrationUser.UserName && c.Password == registrationUser.Password);
if (ldetails == null && pdetails == null)
{
return NotFound();
}
return ldetails;
}