简体   繁体   English

Linq to SQL FirstOrDefault不执行SQL查询

[英]Linq to SQL FirstOrDefault does not execute the SQL query

I have a Windows Forms. 我有一个Windows窗体。 I instanciate my data context in the form's constructor. 我在表单的构造函数中实例化数据上下文。 I want to display information about article when I click on a button. 我想在单击按钮时显示有关文章的信息。 Data can be updated externally. 数据可以在外部更新。 The problem is that, in this case, data is not refreshed. 问题在于,在这种情况下,不会刷新数据。

I already know that re-instanciate my data context each time is an option. 我已经知道每次都可以重新实例化数据上下文。 ToList would force to get the refreshed data. ToList将强制获取刷新的数据。 But I really thought that FirstOrDefault() would execute SQL each time... 但是我真的以为FirstOrDefault()每次都会执行SQL ...

I did some log and this is not the case. 我做了一些日志,事实并非如此。 Is there an option over there to force the SQL execution? 那里有强制执行SQL的选项吗? Is there a sort of cache here? 这里有某种缓存吗?

using (var log = new System.IO.StreamWriter("D:\\LOG.TXT", true))
{
    DB.Log = log;

    var article = DB.T_Articles.FirstOrDefault(x => x.NumArticle == 11);
    MessageBox.Show(article.Description);

    var articles = DB.T_Articles.ToList();

    log.WriteLine("----------------------------------");

    DB.Log = null;
}

Here is the log file. 这是日志文件。 We can see that the SQL behind the FirstOrDefault method is here. 我们可以看到FirstOrDefault方法背后的SQL在这里。 We can see that it disappears the second time 我们可以看到它第二次消失了

SELECT TOP (1) [t0].[NumArticle], [t0].[EAN13], [t0].[Minimum], [t0].[Emplacement], [t0].[Fournisseur], [t0].[Qte], [t0].[Description], [t0].[Photo], [t0].[Prix], [t0].[IsEmail]
FROM [dbo].[T_Article] AS [t0]
WHERE [t0].[NumArticle] = @p0
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [11]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.7.2046.0

SELECT [t0].[NumArticle], [t0].[EAN13], [t0].[Minimum], [t0].[Emplacement], [t0].[Fournisseur], [t0].[Qte], [t0].[Description], [t0].[Photo], [t0].[Prix], [t0].[IsEmail]
FROM [dbo].[T_Article] AS [t0]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.7.2046.0

----------------------------------
SELECT [t0].[NumArticle], [t0].[EAN13], [t0].[Minimum], [t0].[Emplacement], [t0].[Fournisseur], [t0].[Qte], [t0].[Description], [t0].[Photo], [t0].[Prix], [t0].[IsEmail]
FROM [dbo].[T_Article] AS [t0]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.7.2046.0

----------------------------------

您可以尝试在FirstOrDefault()之前每次刷新上下文:

Context.Refresh(RefreshMode.StoreWins, [table_name]);

You can reload the found entry , read more about cache busting 您可以重新加载找到的条目,了解有关缓存清除的更多信息

  var article = DB.T_Articles.FirstOrDefault(x => x.NumArticle == 11);
  DB.Entry(article).Reload();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM