假设我有三个这样的类:
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
设置不正确
最佳答案
您有两个可用选项:eager loading
或 lazy loading
.您可以从此 MSDN Article 获得更多关于它们的详细信息
延迟加载通常被认为是最佳实践,因为默认情况下您应该只将需要的内容加载到内存中;然后根据每个查询进行相应调整。
对于延迟加载,您所要做的就是添加 virtual
到有问题的属性(property):
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)
关于c# - 首先在 Entity Framework 代码中查询自定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32284821/