Scenario: I need to insert a record in a database and use the id resulting from that operation for every other operation needed.
So I've created a class that contains all details of the object that needs to be persisted in the database and added an Id field to store the record id returned by the database operation.
public class MetadataObject {
protected long Id { get; private set; }
protected long RegistrationDate { get; private set; }
protected long FileName { get; private set; }
public MetadataObject(string fileName)
{
FileName = fileName;
RegistrationDate = DateTime.Now;
}
}
1) Once I create a MetadataObject
, the Id
property is 0 (not initialized). Then I make the call to the database.
metadata.Id = RegisterMetadataAndReturnId(metadata);
2) Another thing that I could do is to assign a value to the Id
field immediately after I get it back from the database. The method that handles this would look like this
public void RegisterMetadata(MetadataObject metadata)
{
long recordId;
var metadataInsert = CreateStoredProcedure("RegisterMetadata");
metadataInsert.Execute();
[assign recordId with value received from stored procedure]
metadata.Id = recordId;
}
Second version looks better in my opinion, the only doubt I have is if the method calling the stored procedure must make sure the metadata object Id
property is set before exiting. Or is it better if I just return the Id
value and let the calling procedure take care of that.
Is there a better/cleaner way of getting this done?
Id
property is automatically filled in? \$\endgroup\$