【问题标题】:Avoid multiple calls to database with C# & EF Core避免使用 C# 和 EF Core 多次调用数据库
【发布时间】:2020-06-01 16:59:58
【问题描述】:

我有一个要求,我需要根据 Id 显示一个值。为此,我对数据库和不同的表进行了多次调用。是否可以减少调用次数?

我有基于对 DB 的调用发生的切换条件。下面是示例

foreach (var items in table1)
{
    foreach (var item in items.List)
    {
         switch (item.condition)
         {
             case condition1:
             case condition2:
                 item.nvalue= string.Join(",", _context.table1.Where(x => ids.Contains(x.Id)).Select(x => x.Title));
                 break;

             case condition3:
                 item.nvalue= string.Join(",", _context.tabl2.Where(x => secondIds.Contains(x.Id)).Select(x => x.newvalu));
                 break;

             case condition4:
                 item.nvalue= string.Join(",", _context.tabl3.Where(x => someIds.Contains(x.Id)).Select(x => x.oldvalue));
                 break;

             case condition5:
                 item.nvalue= string.Join(",", _context.tabl4.Where(x=>textIds.Contains(x.Id)).Select(x => x.note));
                 break;

             default:
                 item.nvalue= "";
                 break;
         }
     }
 }

提前致谢

【问题讨论】:

  • 这似乎是代码的味道......
  • 你试过了吗? stackoverflow.com/questions/23172888/… 这也适用于 EF 核心。
  • 这可能是可能的,但取决于。 (1) 什么是 EF Core 版本? (2)这里foreach (var items in table1)table1变量的类型是什么--内存集合还是dbIQueryable<>

标签: c# entity-framework-core


【解决方案1】:

要减少调用次数,您至少可以按条件对项目进行分组:

var groups = table1
    .SelectMany(t => t.List)
    .GroupBy(i => switch (i.condition)
     {
         case condition1:
         case condition2: 
             return 1;
         case condition3:
             return 2;
         ......
         default: return 0;
     });
foreach(var group in groups)
{
     string nvalue;
     switch (g.Key)
     {
         case 1:
             nvalue = string.Join(",", _context.table1.Where(x => ids.Contains(x.Id)).Select(x => x.Title));
             break;

         case 2:
             nvalue = string.Join(",", _context.tabl2.Where(x => secondIds.Contains(x.Id)).Select(x => x.newvalu));
             break;
         .....
         default:
             nvalue= string.Empty;
             break;
     }
     foreach(vat item in group)
     {
         item.nvalue = nvalue;
     }
}

【讨论】:

    【解决方案2】:

    如果您想减少数据库调用,并且如果您的表不是太大或者它们是基本表,您可以使用缓存数据将表缓存在内存中。 完整文档在这里:DocumentationWorking with Cache

    希望它能帮助您解决问题。祝你好运。

    【讨论】:

      猜你喜欢
      • 2020-10-09
      • 1970-01-01
      • 2020-11-13
      • 2022-08-09
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      相关资源
      最近更新 更多