通过匹配IQueryable和Dictionary

本文关键字:String Dictionary IQueryable | 更新日期: 2023-09-27 18:17:48

我有一个场景,我需要通过在公共列的基础上提取IQueryable<T>Dictionary<String, String>之间的匹配属性来生成新的List<my_custom_object>

这是我的字典:

DirectoryProfilePropertiesCollection = (Dictionary<String, String>)ApiMethods.GetProfileProperties(OrganizationIdentifier, DirectoryIdentifier, DirectoryUserName, DirectoryUserPassword);

返回以下信息:

Key: samAccountName, Value: hgulzar 
Key: sn,             Value: Hassan
Key: lastname,       Value: Gulzar

这里的键叫做属性名。

我也有一个IQueryable:

var DirectoryMappingsCollection = repository.GetQuery<OrganizationDirectoryMapping>(where => where.OrganizationDirectory.Organization.OrganizationUnit.UnitIdentifier == OrganizationIdentifier && where.OrganizationDirectory.DirectoryIdentifier == DirectoryIdentifier);

OrganizationDirectoryMapping实体有一个名为DirectoryAttribute的属性

当我要匹配它们时,两个集合都有数据。DirectoryProfilePropertiesCollection的配对有AttributeNameAttributeValueDirectoryMappingsCollection的实体OrganizationDirectoryMappingAttributeNameDetailName

我需要得到一个自定义类对象,表示:DetailName, DirectoryAttributeAttributeValue

一直在尝试一些查询,但当我得到异常时卡住了:

Unable to create a constant value of type 'System.Collections.Generic.KeyValuePair`2'. Only primitive types or enumeration types are supported in this context.

问题LinQ嵌套集合查询的异常有点意义,但我仍然卡住。

致意。

我已经试过了:

combinedCol = (from mapCol in DirectoryMappingsCollection
                                                join propCol in DirectoryProfilePropertiesCollection
                                                on mapCol.DirectoryAttribute equals propCol.Key
                                                select new CombinedMappingDataCollection
                                                {
                                                    DetailName = mapCol.DetailRequirement.DetailName,
                                                    AttributeName = propCol.Key,
                                                    AttributeValue = propCol.Value
                                                }).ToList();

通过匹配IQueryable<T>和Dictionary<String, String>

假设DirectoryMappingsCollection来自实体框架,您不能在查询中包含字典。实体框架不能将KeyValuePair转换为实际的sql代码。

你可以在DirectoryMappingsCollection中添加. tolist来强制它在你的查询中获取整个表,它应该可以工作。如果您正在处理大型数据集,建议添加。where()来限制数据。

combinedCol = (from mapCol in DirectoryMappingsCollection.ToList()
               join propCol in DirectoryProfilePropertiesCollection
               on mapCol.DirectoryAttribute equals propCol.Key
               select new CombinedMappingDataCollection
               {
                   DetailName = mapCol.DetailRequirement.DetailName,
                   AttributeName = propCol.Key,
                   AttributeValue = propCol.Value
               }).ToList();

参见linq to entity framework: use dictionary in query查询类似问题