Today I was working on some persistence code and quickly put together some code like the following:
Post Updated: Had the wrong code the first time.
public HealthStatus SetStatusEntry( Int32 statusTypeId, DateTime statusDateTime )
{
var healthStatus = new HealthStatus() { StatusTypeId = statusTypeId, StatusDateTime = statusDateTime };
var savedHealthStatus = (HealthStatus)Session.Save( healthStatus );
return savedHealthStatus;
}
When I ran my integration test to ensure the data was saved (yes, I am a bit anal) I was a bit perplexed by the exception which was being thrown “System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'FullNamspace.Goes.Here.HealthStatus'.”. When i first looked at the code and the signature of .Save() all looked ok, then I realized that .Save() does not return the persisted entity but the ID of the entity that was just created.
If you are like me and wanted to return the fully persisted entity out of your method remember you can simply use the persisted entity and this will be good.
Hopes this save some hair for others.
Till next time,
Posted
09-15-2009 6:51 AM
by
Derik Whittaker