Proper method to get an Sobject instance from an Id

What is the “proper” way of getting an object from an Id? The method I use at the moment is SOQL, and that feels wrong…..

Example:

Account account = [SELECT Id FROM Account WHERE Id=:inserted.Account__c];

account.Membership_End__c = Date.today();
account.Membership_Active__c = false;
update account;

I feel like this psudo-code should work:

Account account = new Account(inserted.Account__c);
account.Membership_End__c = Date.today();
account.Membership_Active__c = false;
update account;

So do I just have a massive blind spot, or is this it?

Answer

If you already know the ID of the SObject you want to update then you’re right, there’s no need to waste a query just to get an SObject instance to work with.

Your sample code is very close to working, but you need to remember that the constructors for SObjects are special and accept named arguments, something unique to them in all of apex. Your sample code could be updated to work like so:

Account account = new Account(
    Id = inserted.Account__c,
    Membership_End__c = Date.today(),
    Membership_Active__c = false
);
update account;

or even turned into a single statement:

update new Account(
        Id = inserted.Account__c,
        Membership_End__c = Date.today(),
        Membership_Active__c = false
);

As @BritishBoyInDC points out in recent API versions you could also write this in a longer form. There’s not much benefit to doing this in your case, but there are some cases where it can be useful:

Account account = new Account();
account.Id = inserted.Account__c;
account.Membership_End__c = Date.today();
account.Membership_Active__c = false;
update account;

Attribution
Source : Link , Question Author : Mattisdada , Answer Author : ca_peterson

Leave a Comment