Получение ошибки при сохранении изменений при обновлении объекта с ранними связанными сущностями CRM SDK 2015

Я получаю сообщение об ошибке xrm.saveChanges(). Если я делаю UpdateObject, когда AddObject работает нормально, сначала я думал, что это из-за контекста, поскольку обсуждается в этой теме Dynamics CRM, сохраняющей изменения сущности — получение ошибок, но я попробовал все варианты, обсуждаемые здесь https://msdn.microsoft.com/en-us/library/gg695783.aspx, но ничего не помогло.

Мой код `

        using (var xrm = new XrmServiceContext("Xrm"))
        {
            WriteExampleContacts(xrm);

            //Create a new contact called Allison Brown.
            var allisonBrown = new Xrm.Contact
            {
                FirstName = "Allison",
                LastName = "Brown",
                Address1_Line1 = "23 Market St.",
                Address1_City = "Sammamish",
                Address1_StateOrProvince = "MT",
                Address1_PostalCode = "99999",
                Telephone1 = "12345678",
                EMailAddress1 = "[email protected]"
            };

            xrm.AddObject(allisonBrown);
            xrm.SaveChanges();

            WriteExampleContacts(xrm);



        //Update the e-mail address of Allison Brown and link her to the account Contoso.

        //allisonBrown.contact_customer_accountsParentCustomerAccount = account;
        using (var xrm2 = new XrmServiceContext("Xrm"))
        {

            xrm.Detach(allisonBrown);
            xrm2.Attach(allisonBrown);


            allisonBrown.EMailAddress1 = "[email protected]";
            xrm2.UpdateObject(allisonBrown);
            xrm2.SaveChanges();
        }

        //Update the contact record and then commit the changes to Microsoft Dynamics CRM.
        }

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    /// <summary>
    /// Use all contacts where the email address ends in @example.com.
    /// </summary>
    private static void WriteExampleContacts(XrmServiceContext xrm)
    {
        var exampleContacts = xrm.ContactSet
            .Where(c => c.EMailAddress1.EndsWith("@example.com"));

        //Write the example contacts.
        foreach (var contact in exampleContacts)
        {
            Console.WriteLine(contact.FullName);
        }
    }

Ошибка, которую я получаю,

> Microsoft.Xrm.Sdk.SaveChangesException was unhandled
  HResult=-2146233088
  Message=An error occured while processing this request.
  Source=Microsoft.Xrm.Sdk
  StackTrace:
       at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChanges(SaveChangesOptions options)
       at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChanges()
       at MuslimAidConsoleApplication.Sample.Main(String[] args)           at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.ServiceModel.FaultException
       HResult=-2146233087
       Message=The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://schemas.microsoft.com/xrm/2011/Contracts/Services:request. The InnerException message was 'Error in line 1 position 12522. Element 'http://schemas.datacontract.org/2004/07/System.Collections.Generic:value' contains data from a type that maps to the name 'http://schemas.microsoft.com/xrm/7.1/Contracts:ConcurrencyBehavior'. The deserializer has no knowledge of any type that maps to this name. Consider changing the implementation of the ResolveName method on your DataContractResolver to return a non-null value for name 'ConcurrencyBehavior' and namespace 'http://schemas.microsoft.com/xrm/7.1/Contracts'.'.  Please see InnerException for more details.
       Source=mscorlib

Любая помощь будет оценена


person Asimuddin    schedule 01.07.2015    source источник
comment
Почему вы создаете еще один контекст?   -  person Daryl    schedule 01.07.2015
comment
У меня точно такая же проблема, и она начала происходить, когда я обновился до CRM SDK 2015. Я нашел эту ссылку, но я все еще не могу заставить ее работать social.microsoft.com/Forums/en-US/   -  person Goca    schedule 01.07.2015
comment
Вы достигли чего-нибудь? вот такая же проблема! не могли бы вы поделиться своими результатами?   -  person Muhammad Naderi    schedule 13.10.2015


Ответы (3)


Попробуйте использовать эту версию... У меня работает...

SDK версии 7.0.a Октябрь 2014 г.

http://www.filedropper.com/microsoftdynamicscrm2015sdk

person Eriksson    schedule 07.07.2015

Вы должны включить ранние связанные сущности, позвонив

_serviceProxy.EnableProxyTypes();

в вашем экземпляре OrganizationServiceProxy.

var cred = new ClientCredentials();
cred.UserName.UserName = "your username";
cred.UserName.Password = "your password";
using (var _serviceProxy = new OrganizationServiceProxy(new Uri("https://[your organization service url here]"), null, cred, null))
{
    _serviceProxy.EnableProxyTypes(); // Will throw error on save changes if not here
    var context = new CrmServiceContext(_serviceProxy);

    context.AddObject(new Opportunity() { Name = "My opportunity" });

    context.SaveChanges();
}
person Daniel Hansen    schedule 15.10.2015

Регенерация типов прокси должна решить проблему.

Кроме того, поскольку вы подключены к Интернету, убедитесь, что у вас установлена ​​последняя версия SDK (не нужно искать их, они доступны в NuGet).

person Alex    schedule 15.10.2015