2011-03-02 66 views
0
var Dic = _db.Dictionaries.Single(m => m.int_DictionaryId == id); 
    var DicRef = Dic.DictionaryRefs.Where(m => m.int_DictionaryId == id); 

第二個會調用數據庫還是會基於Dic?asp.net mvc linq清理數據庫調用

回答

0

這取決於。你可以配置你的DataContext進行延遲加載(在需要時進行數據庫調用)或急切加載(一次加載所有內容)。 LINQ到SQL使用延遲加載(或延遲加載)默認:

using (YourDataContext _db = new YourDataContext()) 
{ 
    // This will no load any child object/collection. They are requested 
    // when needed. 
    var Dic = _db.Dictionaries.Single(m => m.int_DictionaryId == id); 

    // Now the DictionaryRefs get loaded from the database 
    var DicRef = Dic.DictionaryRefs.Where(m => m.int_DictionaryId == id).ToList(); 

    // Now the DisplayModes get loaded from the database 
    var DicDisplay = Dic.DisplayModes.Where(m => m.DisplayID = displayId).ToList(); 
} 

您可以關閉延遲加載完全關閉:

using (YourDataContext _db = new YourDataContext()) 
{ 
    _db.DeferredLoadingEnabled = false; 

    // This will load the DictionaryRefs child collection 
    // (and any other child object/collection of Dictionary) as well 
    var Dic = _db.Dictionaries.Single(m => m.int_DictionaryId == id); 

    // No call to the database is needed. DictionaryRefs are already loaded 
    var DicRef = Dic.DictionaryRefs.Where(m => m.int_DictionaryId == id).ToList(); 

    // No call to the database is needed. DisplayModes are already loaded 
    var DicDisplay = Dic.DisplayModes.Where(m => m.DisplayID = displayId).ToList(); 
} 

或者,你可以離開延遲加載,並告訴你的DataContext到熱切僅加載一些關係:

using (YourDataContext context = new YourDataContext()) 
{ 
    DataLoadOptions options = new DataLoadOptions(); 
    options.LoadWith<Dictionary>(d => d.DictionaryRefs); 

    context.LoadOptions = options; 

    // This will load the DictionaryRefs child collection as well, 
    // but other child objects/collection will not me loaded 
    var Dic = _db.Dictionaries.Single(m => m.int_DictionaryId == id); 

    // No call to the database is needed. DictionaryRefs are already loaded 
    var DicRef = Dic.DictionaryRefs.Where(m => m.int_DictionaryId == id).ToList(); 

    // Now the DisplayModes get loaded from the database 
    var DicDisplay = Dic.DisplayModes.Where(m => m.DisplayID = displayId).ToList(); 
} 

使用這些選項,您可以控制對象如何相關的加載和accesse d。還請注意,我要求每個兒童收藏都採用ToList()方法。這是因爲當實際需要訪問查詢時,LINQ to SQL只會調用數據庫。

例如:

using (YourDataContext _db = new YourDataContext()) 
{ 
    var comments = _db.Comments.Where(c => c.PostID = 5); 

    // At this point, no call has been made to the database yet. 

    // Now the database is called, because you want to use the comments 
    foreach(var comment in comments) 
    { 
     ... 
    } 
} 
0

加總,以迫使它運行。

var DicRef = Dic.DictionaryRefs.Where(m => m.int_DictionaryId == id).ToList();