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清理数据库调用
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清理数据库调用
这取决于。你可以配置你的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)
{
...
}
}
加总,以迫使它运行。
var DicRef = Dic.DictionaryRefs.Where(m => m.int_DictionaryId == id).ToList();