我在从与用户表连接的表中加载一些信息时遇到问题,在此论坛上经过其他用户的搜索和帮助后,我决定急于加载。这就是我所做的。因此,在扩展方法中,我更改了这一行:
var LoggedUser = db.Users.Find(userId);
此行:
(据我所知,这是我渴望加载的东西)
var LoggedUser = db.Users.Include(a => a.CarGame).Include(a => a.PackManGame).FirstOrDefault(a => a.Id == userId);
它现在可以工作,但是我读过的所有内容都说它可以关闭延迟加载。但是,即使我继续使用,一切都可以正常工作。据我所知,这没有任何区别。控制器中有无此行均无错误:
db.Configuration.LazyLoadingEnabled = false;
所以我的猜测是我做错了什么。但是呢这是怎么回事?
我的扩展方式:
public static ApplicationUser GetLoggedInUserInDB(this System.Security.Principal.IPrincipal _User)
{
using (var db = new ApplicationDbContext())
{
string userId = _User.Identity.GetUserId();
var LoggedUser = db.Users.Include(a => a.CarGame).Include(a => a.PackManGame).FirstOrDefault(a => a.Id == userId);
// var LoggedUser = db.Users.Find(userId);
return LoggedUser;
}
}
我的控制器:
public class MainPageController : ApiController
{
[Route("Personal_Project/Main_Page_Personal_Project/UserUnfo")]
[ResponseType(typeof(string))]
[Authorize]
public IHttpActionResult GetUserInfo()
{
using (var db = new ApplicationDbContext())
{
var LoggedUser = User.GetLoggedInUserInDB();
db.Configuration.LazyLoadingEnabled = false;
return Ok(new UserInfoModel
{
Name = LoggedUser.UserName,
Reputation = LoggedUser.Reputation,
UserLevel = LoggedUser.UserLevel,
Experience = LoggedUser.Experience,
CalculatedPercentage = LoggedUser.CalculatedPercentage,
CarGameBestScore = LoggedUser.CarGame.BestScore,
PackManGameBestScore = LoggedUser.PackManGame.BestScore,
Avatar = LoggedUser.AvatarPicture
});
}
}
}
我仍处于学习过程中的初学者。 如果有人有时间向我解释发生了什么事,那就太好了!