2016-09-21 41 views
3

我正在學習實體框架,並面對一些時刻與查找()方法我無法理解。從朱莉婭·勒曼的書採取
樣本「編程實體框架:代碼優先」實體框架的Find方法如何工作?

public class Destination 
{ 
    public int DestinationId { get; set; } 
    public string Name { get; set; } 
    public string Country { get; set; } 
    public string Description { get; set; } 
    public byte?[] Photo { get; set; } 
    public ICollection<Lodging> Lodgings { get; set; } 

    public Destination() 
    { 
     Lodgings = new List<Lodging>(); 
    } 
} 

public class Lodging 
{ 
    public int LodgingId { get; set; } 
    public string Name { get; set; } 
    public string Owner { get; set; } 
    public bool IsResort { get; set; } 
    public Destination Destination { get; set; } 
} 

我的數據在以下幾個方面工作:

var destination = organizationDbContext.Destinations // case # 1 
       .Include("Lodgings") 
       .First(p=>p.DestinationId==1); 

var destination = organizationDbContext.Destinations.Find(1); // case # 2 
  1. 爲什麼我可以」在Include()調用後的第一種情況下調用Find()方法,但可以使用Where()和First()?
  2. 如果我在Find()方法中使用第二種情況,在這裏我不能調用Include()方法到寄宿,所以我應該如何加載相關的寄宿?

    1. 什麼是應該做的正確的方法:找一個對象,並加載所有相關的內部對象(一到多)

    我的問題可以用另一種方式來表達?

  3. 什麼是正確的做法:加載所有對象(集合A)和內部相關對象(集合A.I),然後通過(A)中的id找到一個?
+1

據我所知'IEnumerable的'不包含方法'Find'但' DbSet '確實。這就是爲什麼它在#2的情況下 – Fabjan

回答

4

關鍵是Find首先在上下文的本地緩存中搜索。如果找不到匹配,則會向db發送查詢。

DbSet上的查找方法使用主鍵值嘗試查找由上下文跟蹤的實體 。如果在 上下文中未找到實體,則將查詢發送到數據庫以在那裏查找實體 。如果在數據庫中的上下文或 中未找到實體,則返回空值。

我認爲這是IQueryable上沒有Find的內部解釋。 當您使用下面的代碼EF總是發送一個請求到DB:

var destination = organizationDbContext.Destinations // case # 1 
       .Include("Lodgings") 
       .First(p=>p.DestinationId==1); 

更多的相關信息:https://msdn.microsoft.com/en-us/data/jj573936.aspx

3

的問題是,我們使用不同類型和該類型中的一種含有方法查找,而另一個不:

1.

var destination = organizationDbContext.Destinations // case # 1 
       .Include("Lodgings") // type here is IQueryable<T> no method Find defined 
       .First(p=>p.DestinationId==1); 

2.

         // type here is DbSet<T> with defined method Find 
var destination = organizationDbContext.Destinations.Find(1);