Get the Identity of the last entered record

Mar 20, 2011 at 2:49 AM
Edited Mar 20, 2011 at 2:55 AM

Just got nHydrate - it looks great  - just doing some initial testing.  Everything generates up perfect - no problems.

My thinking is probably messed up on how nHydrate works  - this what I am trying to do...

I have a 1 - m relationship between Facility table [PK FacilityID]  and Structure table[FK FacilityID]

How do I get the  FacilityID value of a record just added so I can use it to immediatly add a related record to the Structure table?

 private void button1_Click(object sender, EventArgs e)
            string facName = "T1111111111"; 
            var facilityCollection = new FacilityCollection();
            var facility = facilityCollection.NewItem();
            facility.FacilityName = facName;
            facility.FacilityType = "ZZ";
            facility.Active = "T";
          ->  int jusAddedFacilityID = ??

            var stuctureCollection = new StructureOHCollection();
            var structure = stuctureCollection.NewItem();
          ->  structure.FacilityID = justAddedFacilityID;
Mar 20, 2011 at 8:26 PM

Maybe it is so easy you missed it. Just access the property! After you save the collection the facility object's property are set to their database values. There is nothing to do. They are already there. So you like

int jusAddedFacilityID = ??

can be changed to

int jusAddedFacilityID = facility.FacilityId

Actually you do not even need to save it first. Using the NHDAL (which you are) the property can be used on related objects even though it is not set to the real database value. Auto-numbers start at -1 and work backward in memory until they are saved then they are reset to the database values. However in any case if you add a new related object and set its foreign key to the PK of the first object, the framework just knows how to handle it. An added benefit is that you can save multiple object types in one database transaction. I have rewritten your code to do this.

//Create new facility collection, implicit subdomain is created
var facilityCollection = new FacilityCollection();

var facility = facilityCollection.NewItem();
facility.FacilityName = "T1111111111";
facility.FacilityType = "ZZ";
facility.Active = "T";

//Add new related object in same subdomain
var stuctureCollection = facilityCollection.SubDomain.GetCollection<StructureCollection>();
var structure = stuctureCollection.NewItem();
structure.FacilityID = facility.FacilityId; //Value is -1 in memory but this is OK

//Saving any collection saves the whole subdomain

//The FacilityId is now set to the database value after save!
System.Diagnostics.Debug.Assert(facility.FacilityId > 0, "Something is wrong");
Mar 20, 2011 at 9:49 PM

Thanks!  you have a winner working here.