Fetch entity was successful?

Posts   
 
    
ABOH
User
Posts: 148
Joined: 06-Sep-2011
# Posted on: 18-Oct-2012 20:53:51   

Hello,

I need to return null to my code if fetching an entity from the database was unsuccessful due to an invalid primary key; No record with the primary key exists. I found a few postings, but the suggestions didn't work. In the end, I implemented the following code. Is it the proper way to detect that a fetch of an entity resulted in a valid entity? If the customerId does not exist, I need to return a null. If the fetch was successful due to an existing customerId, I need to return the fetched entity.

Thank you for your help, Mike


            var entity = new CustomerEntity(customerId);
            Adapter.FetchEntity(entity);

            // The boolean result of adapter.FetchEntity represents the following:
            // True: the Fetch was successful (whether or not the row exists in DB).
            // So you can receive true and still the entity is IsNew=true.
            //
            // False: the Fetch was not successful (whether or not the row exists in DB). 
            // If you receive false maybe there is a problem with the query, maybe there 
            // is an authorization restriction.
            //
            // So, check the IsNew property of the entity. 
            // If after fetch IsNew=false, then the row exists on DB, 
            // If IsNew=true, the row doesn't exits in DB so the entity automatically is set as new.    
            return ((entity.IsNew && entity.Fields.State == EntityState.OutOfSync) ? null : entity);
daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 19-Oct-2012 06:37:23   

Mike, that solution is very reasonable. It always returns the entity if it was fetched, null otherwise.

David Elizondo | LLBLGen Support Team