1
votes

I am using the Dynamics CRM 2011 C# SDK to write and read data from my on premise DynamicsCRM 2011.

I am currently starting out with this basic example from https://msdn.microsoft.com/en-us/library/gg695803%28v=crm.5%29.aspx

So, creating new Account or Contact and writing it to the Dynamics seems to be no problem and works like this:

var companyTest = new Xrm.Account
{
  Name = "Company Test1",
  AccountNumber = "1",
  Address1_Country = "D",
  Address1_City = "M",
  Telephone1 = "12345678",
  EMailAddress1 = "[email protected]"
};

 xrm.AddObject(companyTest);
 xrm.SaveChanges();

Now I don't fully understand how I can change some information on the Account I created.

So I tried this:

var companyTest = new Xrm.Account
{
  Name = "Company Test1",
  AccountNumber = "1",
  Address1_Country = "D",
  Address1_City = "M",
  Telephone1 = "12345678",
  EMailAddress1 = "[email protected]" // change the email for instance
};

xrm.UpdateObject(companyTest);
xrm.SaveChanges();

But when doing this I get the following error: 'System.InvalidOperationException'

How do I do this properly?

Also, I would be very grateful if someone could recommend a book or a video course on DynamicsCRM SDK.

1

1 Answers

2
votes

in your examples you are using early bound and the XrmContext to add and modify the account.

If you already have the account inside the context (meaning you are executing the update right after you create it, you just need to change the values inside the companyTest:

var companyTest = new Xrm.Account
{
  Name = "Company Test1",
  AccountNumber = "1",
  Address1_Country = "D",
  Address1_City = "M",
  Telephone1 = "12345678",
  EMailAddress1 = "[email protected]"
};

 xrm.AddObject(companyTest);
 xrm.SaveChanges();

companyTest.AccountNumber = "2";
xrm.UpdateObject(companyTest);
xrm.SaveChanges();

if you are doing the update of a record that is not inside the context yet, you will need to provide the Id of the record, something like this:

Guid accountId = new Guid(""); // account id here
var companyTestUpdate = new Xrm.Account
{
  Id = accountId,
  AccountNumber = "2"
};

xrm.UpdateObject(companyTest);
xrm.SaveChanges();

If you are just starting with CRM SDK and CRUD operations, I suggest to use late bound and the IOrganizationService instead of XrmContext, it's easier.