I'm getting the "Save unsaved transient entities" error in NHibernate. I have an aggregate root, neighborhood
that contains addresses
and person
, here's some quick pseudo code to explain the relationship:
public class Neighborhood {
public virtual int Id { get; set; }
public virtual IList<Address> Addresses { get; set; }
}
public class Address {
public virtual int Id { get; set; }
public virtual string Address { get; set; }
public virtual Person Person { get; set; } //Assume only one person per address
}
public class Person {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
In my Neighborhood map I have:
mapping.HasMany(x => x.Addresses)
.Inverse()
.KeyColumn("NeighborhoodFk")
.Cascade.All()
.AsBag();
In my code I will often want to create a and associate an Address and Person at the same time:
var address = new Address();
var person = new Person();
var address.Person = person;
var neighborhood = neighborhoodRepository.Get(id);
neighborhood.Add(address);
neighborhoodRepository.DbContext.BeginTransaction();
neighborhoodRepository.SaveOrUpdate(neighborhood);
neighborhoodRepository.DbContext.CommitTransation();
I will get the "unsaved transient entities" error on the Person
entity because it is attached to the transient entity Address
.
The only way I can see around this is to save the address
first, make another call to the database to update neighborhood
after the update, search for the address
I just added, attach the person
and then save again.
Is there something I'm missing to make this easier? This seems like a common use case and I don't want to be making a bunch of roundtrips to the database.