【问题标题】:Why Does the Entity Framework make so Many Roundtrips to the Database?为什么实体框架对数据库进行如此多的往返?
【发布时间】:2009-10-02 22:43:00
【问题描述】:

我正在重写我的应用程序以使用实体框架。我感到困惑的是我正在编写的代码看起来像是对 sql 服务器造成了不必要的麻烦。例如,我有一个类似于 SO 的问答网站。当我添加一个问题的答案时——这是我使用的代码:

var qu = context.question.where(c => c.questionID == 11).First();  //Database call here
var answer = new answer();
answer.title = "title here";
answer.desc = "desc here";
answer.question = qu;
context.SaveChanges();   //Database call here

在上面的代码中有 2 个数据库调用对吗?如果是这样,为什么我不能直接添加问题的答案?比如

var ans = answer.Createanswer (0, "title here", "desc here", questionID)
context.SaveChanges();

有没有办法最小化所有的数据库调用?

【问题讨论】:

    标签: c# asp.net-mvc entity-framework linq-to-entities


    【解决方案1】:

    正如 EF 设计师之一的 AlexJ 所解释的那样 http://blogs.msdn.com/alexj/archive/2009/06/19/tip-26-how-to-avoid-database-queries-using-stub-entities.aspx

    这一切都属于“优化”领域,这并不像看起来那么简单

    使用简单的方法,SQL 将执行读取操作以加载 FK(问题)并缓存结果,然后在单独的命令上执行插入操作,该操作应使用缓存的 FK 结果

    使用附加的 FK 方法仍然会导致服务器对 FK 执行读取操作,这只是意味着少了一次到 SQL Server 的往返。那么问题就变成了——随着时间的推移,往返是否比增加的代码复杂性更昂贵?

    如果应用程序和 SQL Server 在同一台机器上,这个开销非常小

    此外,如果 FK 是大型或宽表上的聚集索引,则 IO 开销可能比仅针对 FK 值的单独标准索引高得多 - 假设查询优化器正常工作:-)

    【讨论】:

      【解决方案2】:

      您实际上不需要加载问题来设置关系。相反,您可以只使用 EntityReference

      例如

      Answer.QuestionReference = new EntityReference<Question>();
      Answer.QuestionReference.EntityKey 
        = new EntityKey("MyContextName.Question", "Id", questionId); 
      

      我个人使用扩展方法来设置实体键

      public static void SetEntityKey<T>(this EntityReference value, int id)
      {
         value.EntityKey = new EntityKey("ContextName." + typeof(T).Name, "Id", id);
      }
      

      所以它看起来像这样。

       Answer.QuestionReference = new EntityReference<Question>();
       Answer.QuestionReference.SetEntityKey<Question>(questionId); 
      

      【讨论】:

      • 你不能在调用 SetEntityKey 时使用 'this EntityReference' 来避免显式 吗?
      【解决方案3】:

      可以做到,但在 .NET 3.5 中非常痛苦。他们在 .NET 4.0 中使这变得更加容易。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-27
        • 1970-01-01
        • 2017-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多