不包括 returns null 的 LINQ

LINQ without Include returns null

为什么 LINQ 没有 Inlcude returns null 以引用另一个模型?

型号

public class ApplicationUser : IdentityUser
{
    public FilePath FilePath { get; set; }
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }

}

public class FilePath
{
    public int FilePathId { get; set; }
    [StringLength(255)]
    public string FileName { get; set; }
    public FileType FileType { get; set; }
}

public enum FileType
{
    Avatar = 1, 
    Photo = 2,
    Study = 3
}

控制器

private ApplicationDbContext db = new ApplicationDbContext();

public ActionResult Details(string id)
{
    //...

    ApplicationUser appUser1 = db.Users.Find(id);
    ApplicationUser appUser2 = db.Users.Include(i => i.FilePath).SingleOrDefault(i => i.Id == id);
    if(appUser1.FilePath == null); //null
    if(appUser2.FilePath == null); //not null, has all data
    return View(appUser2);
}

您应该将 FilePath 属性 标记为 virtual 以使延迟加载工作:

public virtual FilePath FilePath { get; set; }

顺便说一句: 你的问题应该改成'Entity Framework without Include returns null'。

Entity Framework != LINQ。 LINQ 是一个更高级别的概念,而 Entity Framework 只是实现了一个 LINQ 提供程序,因此您可以使用 linq 语法查询数据库。