Free one-to-many nhibernate

I have a one-to-many relationship and can't get the cascade to work, as soon as I set up the cascade, I just get "object references with an unsaved temporary instance ...".

My mapping is as follows

public class SharedDetailsMapping : ClassMap<SharedDetails> { public SharedDetailsMapping() { Id(x => x.Id).GeneratedBy.Identity(); HasMany(x => x.Foos); } } public class FooMapping : ClassMap<Foo> { public FooMapping() { Id(x => x.Id).GeneratedBy.Identity(); References(x => x.SharedDetails).Cascade.SaveUpdate(); } } 

Classes like this

 public class Foo { public Foo() { SharedDetails = new SharedDetails(); SharedDetails.Foos.Add(this); } public Foo(SharedDetails sharedDetails) { SharedDetails = sharedDetails; SharedDetails.Foos.Add(this); } public virtual Guid Id { get; set; } public virtual SharedDetails SharedDetails { get; set; } } public class SharedDetails { public SharedDetails() { Foos = new List<Foo>(); } public virtual Guid Id { get; set; } public virtual IList<Foo> Foos { get; set; } } 

Then I want to create Foos without having to first save the SharedDetails if this is a new Foo, for example:

 using (var transaction = _session.BeginTransaction()) { var shared = new SharedDetails(); var fooOne = new Foo(shared); _session.SaveOrUpdate(fooOne); var fooTwo = new Foo(shared); _session.SaveOrUpdate(fooTwo); transaction.Commit(); } 

I can’t understand what I did wrong, it works with a nurse if I save SharedDetails first, but that’s why I have the Cascade setting.

+4
source share
1 answer

In SharedDetailsMapping , change HasMany to add .Inverse() :

 public class SharedDetailsMapping : ClassMap<SharedDetails> { public SharedDetailsMapping() { Id(x => x.Id).GeneratedBy.Identity(); HasMany(x => x.Foos) .Inverse(); } } 

This tells NHibernate that Foo has a relation that will help it keep the objects in the relation in the correct order (in this case, SharedDetails must be saved first so that we have our identifier when Foo saved).

Additional information about the target / when to use the reverse: NHibernate inverse - what does it mean?

TL Version: DNR:

If you have bidirectional relationships in your classes (HasMany on the one hand, references to the other), HasMany should have .Inverse() .

+6
source

Source: https://habr.com/ru/post/1442460/


All Articles