NHibernate Assigned ID for parent and identity ID for child - nhibernate

I'm using NHibernate. I have a parent class with Assigned ID and child class with identity Id. I create a new parent class, assign Id to it, then create a new collection of child object. When I call session.Save(parent), I found only parent object is saved, child collection is not saved. It seems that child object must also be saved one by one.
Sometimes I have reversed situation, parent with identity Id and child with assigned Id, also sometimes both parent and child are assigned Id.
I want to confirm is there any way that I always call Session.Save or Session.Update for parent, and NH can deal with the child collection automatically?
Thanks

Actually, you need add some code to get help but just idea for you ;
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="YourNameSpace" assembly="YourAssemblyName">
</class>
</hibernate-mapping>

Related

Nhibernate Identity Skips a thousand

i have an application and the main object have an identity like always. in the database the ids are saved in order increased by 1 as expected 1,2,3,4,5,6 .... N... as expected
but when showed in the view the ids are different like 1 to 12 and then they jump a thousand to 1012
the weirdes is that when i debugg it and i do the Session.Query().ToList();
the ids's are bad, and they just came from the database, i haven't map them or anything.
and if i query by id the object is retrieved it correctly.
public class BaseModel {public virtual int Id { get: set; }}
public class WorkOrder: BaseModel {}
and my Mapping
<?xml version="1.0" encoding="utf-8" ?>
<id name="Id">
<generator class="identity" />
</id>
the app is in production, and we have been creating/updating/deleting several work orders many times, and i had this problems before while developing, but it came back.
is it because the ids is inherited by a base model, or is it any kind of bug of Nhibernate?
The identity generator means that the database will generate the ids. I suggest take a look at the column definition there.

How to query a foreign key column with NHibernate, without retrieving the related entity

Say I have two classes: Parent and Child. A Parent has a property Children, which is of course a collection of Child objects.
Child doesn't have a ParentId property. It does have a Parent property.
So, my NHibernate mapping for Child includes:
<many-to-one name="Parent" class="Parent" column="ParentId" cascade="save-update" />
And my Parent mapping includes:
<bag name="children" access="field" inverse="true" cascade="all-delete-orphan">
<key column="ParentId" />
<one-to-many class="Child" />
</bag>
Now here's what I want to do: I want to get all the Child objects with a certain ParentId. I know I can first get the Parent and then return its Children property. But what if I'd want to query the Child table directly?
If it would be a mapped property (for example, Name), I could use NHibernate's criteria, but in this case, ParentId isn't mapped.
I tried using something like:
criteria.Add(Restrictions.Eq("Parent.Id", 1));
But that doesn't work. I resorted to using SQLCriterion (as explained here), but a friend/colleague got me thinking there must be a better way.
Any ideas? Something with projections and Restrictions.EqProperty?
You have to alias the association path. This will return a proxy for Parent assuming that are using lazy loads. You can access the parent's Id property without triggering a load.
return _session.CreateCriteria<Child>()
.CreateAlias("Parent", "parent")
.Add(Restrictions.Eq("parent.Id", parentId))
.List<Child>();
I've done this using query over. Here is an example:
Child foundChild =
session.QueryOver<Child>()
.Where(x => x.Parent.Id == 1234).SingleOrDefault<Child>();
I think it can be done via Criteria like this:
criteria.Add(Restrictions.Eq("Parent", Session.Load<Parent>(1));

Nhibernate save update delete relations

I have a product that has 1 or more product relations.
Entities: Product and ProductRelation
So product has a property List(Of ProductRelation)
Now I have a checkboxlist where I can select a number of products that I want to assign to this product.
When I add a new collection of ProductRelations with the new products, It should delete all old relations and save the new one. But this does not work. It does not delete the old one and also not saves the new one.
I have used the following hbm.xml
<bag name="RelatedProduct" inverse="true" lazy="true" cascade="all">
<key column="FromID" />
<one-to-many class="Kiwa.Objects.RelatedProduct,Kiwa.Objects" />
</bag>
Your hbm file is not visible. :)
But, why do you add a new collection ?
This is the reason why things are going wrong.
You should clear the collection (remove the items from the collection), and just add the new items to the collection, without replacing the collection itself.
You should NEVER replace mapped collection once it has been persisted. NHibernate needs that specific collection instance (which is created / injected by NHibernate during entity load) to track deletes.
You should instead delete / update / replace individual elements (e.g. RelatedProduct instances) within existing collection. If you truly want to delete all the previously saved RelatedProducts and insert new ones (why?), you can clear the RelatedProduct List - but don't replace it with a new List instance.

nhibernate mapping many-to-many: why was the whole bag collections deleted and reinserted?

Nhibernate users, professionals, gurus and developers are expected. Please help !!!
I want to realise a n:m relation between two classes. A student attends in more courses and a course consists of more students as members. I do a bidirectional association many-to-many with bag to get the both lists from each site.
The two Student and Course classes:
public class Student {
// Attributes........
[XmlIgnore]
public virtual IList MyCourses { get; set; }
// Add Method
public virtual void AddCourse(Course c)
{
if (MyCourses == null)
MyCourses = new List<Course>();
if (!MyCourses.Contains(c))
MyCourses.Add(c);
if (c.Members== null)
c.Members= new List<Student>();
if (!c.Members.Contains(this))
c.Members.Add(this);
}
public virtual void RemoveCourse(Course c)
{
if (MyCourses != null)
MyCourses.Remove(c);
if (c.Members!= null)
c.Members.Remove(this);
}
}
public class Course {
// Attributes........
[XmlIgnore]
public virtual IList Members { get; set; }
}
In database there are two tables t_Student, t_Course and a relation table tr_StudentCourse(id, student_id, course_id).
<class name="Student" table="t_Student" polymorphism="explicit">
.....
<bag name="MyCourses" table="tr_StudentCourse">
<key column="student_id" />
<many-to-many class="Course" column="course_id" not-found="ignore" />
</bag>
</class>
<class name="Course" table="t_Course" polymorphism="explicit">
.....
<bag name="Members" table="tr_StudentCourse" inverse="true">
<key column="course_id" />
<many-to-many class="Student" column="student_id" not-found="ignore" />
</bag>
</class>
Course was chosen as inverse in the bidirectional association. I did the same as example (Categorie, Item) in section 6.8 of nhibernate documentation. So I saved the student object after inserting a course in the list MyCourses by calling the Add/Remove-method.
Student st1 = new Student();
Course c1 = new Course();
Course c2 = new Course();
st1.AddCourse(c1);
st1.AddCourse(c2);
session.saveOrUpdate(st1);
That works fine, the st1, c1 and their relation (st1,c1) can be find in the database. The relation datasets are (id=1, st1.id, c1.id) and (id=2, st1.id, c2.id).
Then I add more courses to the object st1.
Course c3 = new Course();
st1.AddCourse(c3);
session.saveOrUpdate(st1);
I can see the 3 relation datasets, but the two old relations were deleted and new three were created with another new id. (id=3, st1.id, c1.id), (id=4, st1.id, c2.id) and (id=5, st1.id, c3.id). There are not dataset with id=1 and 2 more in relation table.
The same by deleting if I remove a course from student.MyCourse and then save the student object. All collection was also deleted and recreated a new list which less one deleted element. That problem makes the id in the relation table increates very fast and a have troble by doing a backup of relation.
I have looked some days in internet, documentation and forums to find out why the whole old collection was deleted and a new as created by each changing, but I was not successful. It is a bug from nhibernate mapping or did I do any wrong?
I am very very grateful to your help and answer.
Nhibernate documentation http://nhforge.org/doc/nh/en/index.htm
NHibernate can't create, delete or
update rows individually, because
there is no key that may be used to
identify an individual row.
By note from "6.2. Mapping a Collection"
As soon as you have id in tr_StudentCourse you can try using indexed collections, i.e. replace <bag> with <map> or similar and add <index> element to the mapping:
<index
column="id"
type="int"
/>
or even create a special entity for the relation table to use with <index-many-to-many>.
This is what I've found on the NHibernate website:
Hibernate is deleting my entire
collection and recreating it instead
of updating the table.
This generally happens when NHibernate
can't figure out which items changed
in the collection. Common causes are:
replacing a persistent collection
entirely with a new collection
instance passing NHibernate a manually
constructed object and calling Update
on it.
serializing/deserializing a
persistent collection apparently also
causes this problem.
updating a
with inverse="false" - in this case,
NHibernate can't construct SQL to
update an individual collection item.
Thus, to avoid the problem:
pass the same collection instance that
you got from NHibernate back to it
(not necessarily in the same session),
try using some other collection
instead of <bag> (<idbag> or <set>),
or try using inverse="true" attribute
for <bag>.

Fluent NHibernate HasMany not updating the FK

I'm using latest Fluent NHibernate lib (0.1.0.452) and I have a problem with saving child entitites.
I think this is rather common scenario... I've got a parent with mapping:
HasMany<Packet>(x => x.Packets)
.Cascade.All()
.KeyColumnNames.Add("OrderId");
and a simple Packet class that (in a domain model and FNH mapping) doesn't have any reference to the parent.
What gets generated is a correct Packets table that contains a column named OrderId.
What doesn't work is the saving.
Whenever I try to save parent object, the children are also saved, but the FK stays untouched.
I checked the SQL and in INSERT statement the OrderId doesn't even appear!
INSERT INTO KolporterOrders (CargoDescription, SendDate, [more cols omitted] ) VALUES ('order no. 49', '2009-04-22 00:57:44', [more values omitted])
SELECT LAST_INSERT_ID()
INSERT INTO Packets (Weight, Width, Height, Depth) VALUES ('To5Kg', 1, 1, 1)
SELECT LAST_INSERT_ID()
As you see the OrderId is completely missing in the last INSERT.
I also checked the generated NH mapping and it seems it's ok:
<bag name="Packets" cascade="all">
<key column="OrderId" />
<one-to-many class="Company.Product.Core.Packet, Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</bag>
I tried setting Cascade to different values. I even added References to the PacketMap (FNH mapping class).
Any ideas why the OrderId is not being inserted?
Edit: forgot to mention: I'm using MySQL5 if it matters.
Edit2: The above FNH mapping generates hbm with bag (not a set) - I edited it.
The C# code used for saving:
var order = new Order();
NHSession.Current.SaveOrUpdate(order); //yes, order.Packets.Count == 1 here
///Order.cs, Order ctor
public Order()
{
CreateDate = DateTime.Now;
OrderState = KolporterOrderState.New;
Packets = new List<Packet>();
Packets.Add(new Packet()
{
Depth = 1,
Height = 1,
Width = 1,
Weight = PacketWeight.To5Kg
});
}
the session gets flushed and closed at EndRequest.
Ok, my fault. I was testing it in ApplicationStart of global.asax, so the Request hadn't been created so the session wasn't flushed. I realised it when I tested it on a simple ConsoleApp project when I saw that flushing actualy causes the FK col update.
Anyway: thanks for help!
In a "vanilla" parent-children object model, you must update the child's object's reference to the parent in order to cause NHibernate to update the child record's reference to the parent.
In an "inverted" parent-children object model, you must modify the parent's collection of children objects in order to cause NHibernate to update the child records' references to the parent.
It seems you may want to be using an "inverted" parent-children object model.
In the XML mapping, you need
<set name="Packets" cascade="all" inverse="true">
<key column="OrderId" />
<one-to-many class="Company.Product.Core.Packet, Core,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</set>
In the Fluent mapping, you need
HasMany<Packet>(x => x.Packets)
.Cascade.All()
.Inverse()
.KeyColumnNames.Add("OrderId")
;
This is really strange. You should check subsequent Updates, NHibernate sometimes updates foreign keys afterwards, and then it doesn't appear in the insert.
Make sure that OrderId does not have several meanings on the Packets table. To check this, change the name of OrderId to something else.
Cascading has nothing to do with it. It only controls if you need to save the child explicitly.