Foreign key is null when NH save the childs collection

I try to map NHibernate to an existing database structure. Unfortunately I can not change the existing structure.

First I'll give some background and then explain the problem itself

Relational analysis is quite simple: Foreign key is null when NH save the childs collection

Log is the main Entity. he has one-to-one relationship with Form. the foreign key is FormID.

Buyer & Seller are collection of the form entity. The application should save the form entity together with the buyers and the sellers.

The problem is the primary key consisting of the Buyer & Seller entity. The key composite from ForegineKey- FormID and an intenal ordering int number- tdNum

This is reflected in the following form FNH mapping

public class FormLogMap : ClassMap<FormLog> { public FormLogMap() { Table("BillOfSaleLog"); Id(x => x.FormId).Column("FormID").GeneratedBy.Native(); .... .... References<Form>(x => x.Form, "FormID").LazyLoad().ReadOnly(); } } public class FormMap : ClassMap<Form> { public FormMap() { Table("BillOfSaleForm"); Id(x => x.Id).Column("FormID").GeneratedBy.Foreign("Log"); ... ... HasOne<FormLog>(x => x.Log).Cascade.All(); HasMany(x => x.Buyers).KeyColumn("FormID").Inverse().Cascade.All(); HasMany(x => x.Sellers).KeyColumn("FormID").Inverse().Cascade.All(); } } public class BuyerMap : ClassMap<Buyer> { public BuyerMap() { Table("BillOfSaleBuyer"); CompositeId() .KeyReference(x => x.Form, "FormID") .KeyProperty(x => x.InnerOrderId, "tdNum1"); .... .... } } Seller is exectly the same

The problem occurs when I try to save the entity by the Edit Action I'm using MVC to get the user data and make it an object. The binding works fine and makes the object along with the collections.

But when I save an entity receive the following error: Foreign key is null when NH save the childs collection

I expect NHibernate be smart enough to set the Buyer & Seller foreign keys. But in fact they remain without value.

The problem can be solved by setting foreign keys manually as the following code:

//i have to set the form proerty in the childs //without of the lines NH will try to save the childs it with FormID = null foreach (var buyer in form.Buyers) { buyer.Form = form; } foreach (var seller in form.Sellers) { seller.Form = form; }

But I'm looking for an elegant and correct solution

Thank you for reading

--------------Solutions-------------

You don't show the code for adding a Buyer or Seller to a Form but it should look like this:

form.Buyers.Add(buyer);
buyer.Form = form;

Because Form is the inverse side of the relationships, you have to set the reference to Form on the many side. You should do this anyway so that the in-memory objects are correct. If the Buyer and Seller objects are already persistent in the same ISession than that should work.

According to this related question, HHibernate does not support cascade working with a composite key (as you have in BuyerMap). One of the answers does contain a hack to workaround this, but you will end up with a redundant column.

Category:nhibernate Time:2010-10-21 Views:0

Related post

  • How to set a foreign key to null ? (symfony) 2010-11-29

    I have a form with an input which is optionnal but I can't valid the form if the user don't fill it because it's a foreign key and Doctrine shows me an error. SQLSTATE[HY000]: General error: 1452 Cannot add or update a child row: a foreign key constr

  • How can I delete rows where its foreign key is NULL? 2011-03-15

    I have two tables with names tab1 and tab2. tab1's primary key is price and price is foreign key in tab2 and it is on delete set null. When I delete one of primary key from tab1 that exists in tab2 the respective foreign key is set to NULL. Now I wan

  • Foreign keys and NULL in mySQL 2010-05-10

    Can I have a column in my values table (value) referenced as a foreign key to knownValues table, and let it be NULL whenever needed, like in the example: Table: values product type value freevalue 0 1 NULL 100 1 2 NULL 25 3 3 1 NULL Table: types id n

  • Setting a foreign key to null when using entity framework code first 2011-06-21

    I'm using the database first implementation of Entity Framework Code First as the data layer for a project, but I've run into a problem. I need to be able to set a foreign key to null in order to remove an association in the database. I have 2 object

  • SQL Server / Entity Framework foreign key set null on delete 2014-12-08

    I've an issue on my database design with MSSQL, I'm using code first and here is the part of my entities : [Table("Document")] public class Document { [Key] public int Id { get; set; } public Boolean? IsPrivate { get; set; } public String Url { get;

  • fluent-nhibernate automapping foreign key inserts null. 2010-09-04

    I have a class called Worker public class Worker : BaseEntity { public virtual int WorkerID { get; set; } public virtual string Name { get; set; } public virtual IList<Indemnification> Indemnifications { get; set; } } public class Indemnificati

  • Help understanding foreign key not-null=true and inverse behavior in a zero-to-one relationship with NHibernate 2011-05-31

    I'm trying to get NHibernate to use the many side of a collection to manage a bidirectional association to model a zero-to-one relationship. Parent Class and Map: public class Parent { private ICollection<Child> children; public Parent() { this

  • Can table columns with a foreign key be null? 2010-03-02

    For example, I have a table which has several ID columns to other tables. I want a foreign key to force integrity only if I do put data in there. If I do an update at a later time to populate that column then it will still check the constraint (this

  • Hibernate: How to delete child records instead of setting foreign key to null 2010-09-19

    I have a User and a set of Authorities in a one-to-many relationship: User.hbm.xml: <set name="authorities" table="authorities" cascade="all-delete-orphan"> <key column="user_id" /> <one-to-many class="com.ebisent.domain.Authority" /

  • Fluent NHibernate Foreign Key is Null, from lookup table 2010-11-04

    I have a lookup table that contains products (Product table) a CustomerOrder table that contains order details and an OrderLines table that contains a line per product ordered. So the entities look something like this OrderLine Id ..stuff.. Product P

  • Updating a foreign key to Null value using nhibernate 2011-01-31

    I have two table BuildGroup and table DocumentTemplate. DocumentTemplate table has BuildGroupId as foreign key which is nullable. In a certain senario I update BuildGroupId in DocumentTemplate table. public bool EditDocTempForBldGrp(int docId, int bl

  • Nested Form Update in Rails 3 sets foreign key as NULL 2011-06-21

    I am trying to update a user record using a formtastic nested form. Its structure is as ollows User Admin Address When I send the form to update details, while updating the address or admin record, the user_id(foreign key) gets set to NULL. This is t

  • Foreign Key is null when insert using Stored Procedure 2011-12-05

    I've created a insert stored procedure with two tables like in the exapmle: Table NameAge CREATE TABLE [dbo].[Assignment3_NameAge] ( userID int PRIMARY KEY IDENTITY(1,1), Name varchar(255) NOT NULL, Age int NOT NULL ) Table Hobbies CREATE TABLE [dbo]

  • Foreign key or null value 2011-12-06

    I have 2 tables: pages and menu I want to have a pointer into menu table as foreign key to pages.id. The problem is that some menu rows don't have a link to page. When someone clicks in the link opens a submenu. How i do this in phpmyadmin? The match

  • Doctrine DQL query - getting rows when foreign key is null 2012-02-22

    I wonder if anyone can help with this Doctrine query. Basically, My query does not return rows where the foreign key is not set or NULL. And I would like to return all rows. Here are 2 schemas Items class Items{ /** * @var integer $id * * @Column(nam

  • Foreign key is null (while it is not) when using linq 2012-03-18

    I am using var s = db.sModels.ToList().First(r => r.Status == CustomStatus.Available); to fetch the first available item. However, when fetched, a foreign key in s turns out to be null. I have connected to the database and saw that the foreign key

  • How to pull row from join when foreign key is null 2011-12-29

    I have a DB table with product information, and a DB table with tax rates. My problem is that I am joining these two tables together, which works great.. until I disable "taxable" on a row for the product DB. Now my query is trying to join, but doesn

  • Foreign Key Constraint is preventing NHibernate from saving child record 2009-05-01

    I have two tables: SupportTicket SupportTicketID SupportTicketDate SupportTicketNote SupportTicketNoteID SupportTicketNoteDate SupportTicketID With a foreign key constraint so I don't have any unassociated Notes...in sql that constraint is working pr

  • SQL SELECT foreign key rows that have no rows in child table 2012-04-24

    I need the following code to still show rows from the AUTHOR table even if they aren't called from any rows in the ALLOCATION table. Currently, the code shows all ALLOCATION rows with the appropriate foreign key data. I need it so that all rows from

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.544 (s). 13 q(s)