C# Linq 嵌套选择不返回所有内容

C# Linq nested selects not returning everything

我正在尝试通过 Linq select 来自多个表的信息。如果我取出最后一个 Api 查询 from apis in Database.PluginApis where apis.PluginId == tenantPlugin.PluginId,则查询有效。如果我把查询放回去,它会导致错误 System.Collections.Generic.KeyNotFoundException: The given key 'Name' was not present in the dictionary. 任何人都能看到我做错了什么吗?

var results = (from tenantPlugin in Database.TenantPlugins
                           where tenantPlugin.TenantId == tenantId

                           select new TenantPlugin
                           {
                               PluginId = tenantPlugin.PluginId,
                               IsEnabled = tenantPlugin.IsEnabled,
                               TenantId = tenantPlugin.TenantId,
                               TenantPluginId = tenantPlugin.TenantPluginId,
                               Plugin = (from plugin in Database.Plugins
                                         where plugin.PluginId == tenantPlugin.PluginId
                                         select new Plugin
                                         {
                                             PluginId = plugin.PluginId,
                                             Name = plugin.Name,
                                             Description = plugin.Description,
                                             ImagePath = plugin.ImagePath,
                                             IsActive = plugin.IsActive,
                                             Apis = (from apis in Database.PluginApis
                                                         where apis.PluginId == tenantPlugin.PluginId                                                             
                                                     select new PluginApi
                                                     {
                                                         Name = apis.Name
                                                     }).ToList<PluginApi>()
                                         }).FirstOrDefault<Plugin>()
                           });

            return results.ToList();

看来您有一个使用 Include() 方法的完美案例。尝试:

var results = Database.TenantPlugins
              .Include(t => t.Plugin.Select(p => p.Apis))
              .Where(t => t.TenantId == tenantId);