想象一下,我有三个这样的课程:
public class Employee {
public int EmployeeId {get;set;}
public string Fname {get;set;}
public File Picture {get;set;}
}
public class Employer {
public int EmployerId {get;set;}
public string Fname {get;set;}
public string WorkingPlace{get;set;}
public File Pictrue {get;set;}
}
public class File {
public int FileId {get;set;}
public byte[] Content {get;set;}
public int Size {get;set;}
}
首先,上面的代码是否正确保存不同实体的文件和图像?然后这是我的上下文类:
public class MyDbContext : DbContext
{
public DbSet<File> Files { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<Employer> Employers { get; set; }
}
当我有这样的查询时:
MyDbContext context = new MyDbContext
var q = from emp in context.Employees
where emp.EmployeeId == 4
select emp;
Console.WriteLine(q.First().Picture.FileId)
我将{0}视为FileId
,而当我查看数据库时,我认为它不是0。
不知怎的q.First().Picture
未正确设置
答案 0 :(得分:2)
您有两种选择:eager loading
或lazy loading
。您可以从MSDN Article
延迟加载通常被认为是最佳实践,因为您应该只在默认情况下将所需内容加载到内存中;然后根据每个查询进行相应调整。
对于延迟加载,您所要做的就是将virtual
添加到相关媒体中:
public class Employee {
public int EmployeeId {get;set;}
public string Fname {get;set;}
public virtual File Picture {get;set;}
}
这应该使您的查询按预期工作;但是,它可能会导致2次数据库调用,这将是低效的。为了解决这个问题,您可以使用.Include<>
MyDbContext context = new MyDbContext
var q = context.Employees.Include(e => e.Picture).Where(e => e.EmployeeId == 4);
var q2 = context.Employees.Include("Picture").Where(e => e.EmployeeId == 4); //Alternative syntax
Console.WriteLine(q.First().Picture.FileId)