首先在實體框架代碼中查詢自定義類型

[英]Querying custom types in entity framework code first


Imagine I have three classes like these :

假設我有三個類:

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;}
}

First, Is above code right way to save files and images of different entities? and then this is my context class:

首先,上面的代碼是保存不同實體的文件和圖像的正確方法嗎?這是我的背景課程:

public class MyDbContext : DbContext
{     
    public DbSet<File> Files { get; set; }
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Employer> Employers { get; set; }
}

When I have query like this :

當我有這樣的疑問:

MyDbContext context = new MyDbContext
var q = from emp in context.Employees
        where emp.EmployeeId == 4
        select emp;
Console.WriteLine(q.First().Picture.FileId)

I get 0 as FileId while I see it's not 0 when I look in database. Somehow q.First().Picture is not set correctly

當我在數據庫中查找時,我得到0作為文件id,但我看到它不是0。不知何故q.First()。圖片設置不正確

1 个解决方案

#1


2  

You have two options available: eager loading or lazy loading. You can get more detail about them from this MSDN Article

您有兩種選擇:快速加載或延遲加載。您可以從這個MSDN的文章獲得更多的細節。

Lazy loading is generally considered best practice, because you should only load what you need into memory by default; and then adjust accordingly on a per query basis.

延遲加載通常被認為是最佳實踐,因為您應該只在默認情況下將需要的內容加載到內存中;然后根據每個查詢進行相應的調整。

For Lazy Loading, all you have to do is add virtual to the property in question:

對於延遲加載,您所要做的就是向所涉及的屬性添加虛擬值:

public class Employee {
  public int EmployeeId {get;set;}
  public string Fname {get;set;}
  public virtual File Picture {get;set;}
}

This should make your query work as expected; however, it will probably result in 2 database calls, which would be inefficient. To address that, you can eager load the data as part of the query using .Include<>

這將使您的查詢工作如預期的那樣工作;但是,它可能會導致兩個數據庫調用,這是低效的。要解決這個問題,可以使用.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)

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/08/29/72a0941182d096e52b2616f18119b303.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com