Question

I have Customer and Profile classes, where one Customer can have many Profiles.

I am using following NHibernate override classes with them:

 public void Override(AutoMapping<Customer> mapping)
    {
        mapping.Table("[Customer]");
        mapping.Id(x => x.Id, "Id").GeneratedBy.Identity();

        mapping.HasMany(x => x.Profiles).Cascade.All().Inverse();

        mapping.Map(x => x.FirstName, "FirstName");
        mapping.Map(x => x.LastName, "LastName");
        mapping.Map(x => x.Email, "Email");            
    }

public void Override(AutoMapping<Profile> mapping)
    {
        mapping.Table("[Profile]");
        mapping.Id(x => x.Id, "Id").GeneratedBy.Identity();

        mapping.References(x => x.Customer, "Customer_Id").Cascade.None();

        mapping.Map(x => x.FacebookProfileLink, "FacebookProfileLink");
        mapping.Map(x => x.ContactPhone, "ContactPhone");          
    }

I am getting following error while inserting Profile object:

Cannot insert the value NULL into column 'Customer_Id', table 'dbo.Profile'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated.

My intence is to insert Customer object before Profile that needs a reference to Customer object. That's why I'm using Inverse attribute. Unfortunately it doesn't work. Any help on this ? Thank you.

Was it helpful?

Solution 2

I found out solution that works for me.

I am saving Customer entity without reference to it's Profiles. Afterwards I'm saving Profile entity.

Works for me even better than solution i wanted to achieve before, as I can check on success of Customer insert and then decide what to do next (save Profile as well or do some validation error).

Thank you all for your answers.

OTHER TIPS

One thing that NHibernate does as a good ORM is to save everything in the relationships so you don't have to save things separately. I think your issue might but in what you are doing when you say 'insert Customer object before Profile that needs a reference to Customer'.

The reality is that you should create the customer, with the profiles needed to be associated to it, and then just save the customer. NHibernate will save all the entities in the right order to make sure the relationships are preserved. Try doing that, first create or retrieve the customer entity, then add/remove the profiles, and then save the customer. Profiles would be saved because of the cascade option you have specified in the mapping.

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top