web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Invalid Directory Key In Linq C# Query MSCRM

(0) ShareShare
ReportReport
Posted on by 242

Hi,

I am trying to get details from linq Query for MSCRM C# i tried with following example

https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/org-service/sample-complex-linq-queries

But its saying 

System.Exception
HResult=0x80131500
Message=System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at Microsoft.Xrm.Sdk.DataCollection`2.get_Item(TKey key)
at lambda_method(Closure , <>f__AnonymousType9`2 , Entity )
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.DynamicInvoke(Delegate project, Object[] args)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.<>c__DisplayClass29_0.<ExecuteAnonymousType>b__1(<>f__AnonymousType0`2 <>h__TransparentIdentifier0)
at System.Linq.Enumerable.<>c__DisplayClass7_0`3.<CombineSelectors>b__0(TSource x)
at System.Linq.Enumerable.<>c__DisplayClass7_0`3.<CombineSelectors>b__0(TSource x)
at System.Linq.Enumerable.<>c__DisplayClass7_0`3.<CombineSelectors>b__0(TSource x)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__97`1.MoveNext()
at Microsoft.Xrm.Sdk.Linq.PagedItemCollection`1.MoveNext()
at DynamicsCRMAPI.Program.searchmemberbyno(String memberno) in D:\test\DynamicsCRMAPI\DynamicsCRMAPI\Program.cs:line 431
Source=DynamicsCRMAPI
StackTrace:
at DynamicsCRMAPI.Program.searchmemberbyno(String memberno) in D:\test\DynamicsCRMAPI\DynamicsCRMAPI\Program.cs:line 447
at DynamicsCRMAPI.Program.Main(String[] args) in D:\aashish\DynamicsCRMAPI\DynamicsCRMAPI\Program.cs:line 28

The Code i am using is

public static void searchm()
{
try
{

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string connStr = ConfigurationManager.ConnectionStrings["CRMOnline"].ConnectionString;
CrmServiceClient conn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connStr);
IOrganizationService _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;


using (


OrganizationServiceContext svcContext = new OrganizationServiceContext(_orgService))
{

var query = from c in svcContext.CreateQuery("contact")
join rk in svcContext.CreateQuery("rdiac_riskobject")

on c["contactid"] equals (Guid)((EntityReference)rk["rdiac_owningparty"]).Id
// join pl in svcContext.CreateQuery("productpricelevel")
// on q["pricelevelid"] equals pl["pricelevelid"]
//join pro in svcContext.CreateQuery("product")
//on q["rdiac_product"] equals pro["productid"]

join salesorder in svcContext.CreateQuery("salesorder")
on c["contactid"] equals (Guid)((EntityReference)salesorder["contactid"]).Id
//join cpl in svcContext.CreateQuery("productpricelevel")
//on childpro["pricelevelid"] equals cpl["pricelevelid"] && q[""]
join pl in svcContext.CreateQuery("pricelevel")
on salesorder["pricelevelid"] equals (Guid)((EntityReference)pl["pricelevelid"]).Id
where (string)c["cn_membernumber"] != ""


select new
{

//memberdetails
cn_membershipnumber = c["cn_membershipnumber"],
cn_membernumber = c["cn_membernumber"],
firstname = c["firstname"],
lastname = c["lastname"],
address1_composite = c["address1_composite"],
telephone1 = c["telephone1"],
telephone2 = c["telephone2"],
emailaddress1 = c["emailaddress1"],
//vehicle details
cn_vinnumber = rk["cn_vinnumber"],
cn_length = rk["cn_length"],
rdiac_chassisnumber = rk["rdiac_chassisnumber"],
rdiac_builtyear = rk["rdiac_builtyear"],
rdiac_vehiclebrand = ((EntityReference)rk["rdiac_vehiclebrand"]).Name,
rdiac_vehiclemodel = ((EntityReference)rk["rdiac_vehiclemodel"]).Name,
rdiac_vehicletype = rk.FormattedValues["rdiac_vehicletype"].ToString(),
cn_transmissionoptionset = rk.FormattedValues["cn_transmissionoptionset"].ToString(),
//converage details
//rdiac_duration = salesorder.FormattedValues["rdiac_duration"].ToString(),
priceplanname = pl["name"],

};


//List<string> intList = new List<string>();

//foreach (var entity in query)
//{
// Console.WriteLine(entity.);
// Console.ReadLine();
//}
foreach (var c in query)
{
System.Console.WriteLine(c); //+ c.childprice);//+ c.childproduct_name + " " + c.childprice+ c.price +

}

System.Console.ReadLine();
//We can simply call query.ToList()
//foreach loop here is to demonstrate item Enumeration

//return intList;
}
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Sid07 Profile Picture
    285 on at

    You are getting "The given key is not present" error. So u need to handle those column scenarios where u r assigning values from entity object i.e. for e.g

    cn_membershipnumber = c["cn_membershipnumber"],

    U can do

    cn_membershipnumber = c.Attributes.Contains("cn_membershipnumber") ? c["cn_membershipnumber"] : "";

    Else u may use Getattributevalue. So some value is null in one of the attribute which u r assigning in linq.

    Hope this helps.

    Please mark if it helped.

    Thanks

  • Suggested answer
    Dynamics365 Rocker Profile Picture
    7,755 on at

    It seems that you are not getting data in one of your field.

    Use contains before assigning it.

    if(c.Attributes.Contains("firstname") )

    {

    firstname=c["firstname"];

    }

    or

    firstname= c.Attributes.Contains("firstname") ? c["firstname"] : "";

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans