c# - 首先在 Entity Framework 代码中查询自定义类型

标签 c# database entity-framework

假设我有三个这样的类:

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 loadinglazy 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/

相关文章:

c# - 如何为多种数据类型创建一个下拉列表?

php - 多对多命名约定

mysql - 为什么我添加 htacess 文件后我的 post 方法只发送 1 行表数据?

entity-framework - Entity Framework 从数据库生成生成空 EDMX

entity-framework - 你如何在 dotnet Core 中使用 DBContext

c# - 让 AppSettingsReader 询问值的类型并返回一个非特定类型的对象有什么意义?

c# - 如何从字符串生成唯一整数?

c# - sonarlint.exe 不是有效的 win32 应用程序

mysql - 在不导出数据的情况下分隔mysql数据库中的数据

c# - WebApi 2.0 项目在哪里存储新用户(使用个人用户身份验证创建时)?