cja
cja

Reputation: 10016

How to get id of saved entity

Dynamics CRM 2011 on premise

I can barely believe I can't find this out by Googling. MSDN is useless.

Here is some C# from a plugin:

integ_creditpayment creditpayment = new integ_creditpayment();
creditpayment.integ_Amount = totalPay;
//set more properties
context.AddObject(creditpayment);
context.SaveChanges();

Now I want to get the value of the id field in integ_creditpayment.

Can I get this immediately from creditpayment.id? (As in, does context.SaveChanges() cause the creditpayment variable to be updated with the new id?)

Upvotes: 0

Views: 2235

Answers (2)

Daryl
Daryl

Reputation: 18895

I'm assuming your real code is more complicated, but there is no need to use the context in your example code:

integ_creditpayment creditpayment = new integ_creditpayment();
creditpayment.integ_Amount = totalPay;
//set more properties
creditpayment.Id = service.Create(creditpayment);

You can also use a type initializer and get rid of your object all together if you'd like:

Guid id = service.Create(new integ_creditpayment
{
    integ_Amount = totalPay;
});

service in this case is of type IOrganizationService

Upvotes: 1

Guido Preite
Guido Preite

Reputation: 15128

After the SaveChanges() you can get the record id with:

Guid justCreatedId = creditpayment.Id;

Upvotes: 0

Related Questions