NHibernate cascade deletes - nhibernate

I have a one-to-many relationship in data model from A to B. But in my domain API I do not expose "B"s on A (since we will never navigate from from A to B), but have a reference from B to A. Now I want to be able to delete all "B"s when A is deleted. Is it possible? Right now NH is trying first to set FK to null, which I don't want, and cannot since column is not nullable.
A = SupplierType
B = BaseProductCoInsurance
public BaseProductCoInsuranceMap()
{
Table("BaseProductCoInsurance");
Id(x => x.Id, "BaseProductCoInsuranceId");
Map(x => x.CoInsurancePercent).Column("CoInsrPrcnt");
References(x => x.BaseProduct, "BaseProductId");
References(x => x.PolicySupplierType, "PlcySupplierTypeID");
References(x => x.InsuredType, "InsuredTypeCode");
}

If you need to be able to cascade delete then you need to let NHibernate know about the relationship. That said you don't need to make the relationship accessible to others. You could of course have a private collection that only NH knows about.
If you make the relationship lazy loaded you shouldn't even see a performance hit from this.
Another option to consider is to just modify your delete method to also delete the other entity.

Related

Fluent NHibernate - Composite Mapping from Child Table

I am sure someone has to have done this before - looking at the previous queries it possibly cannot be done with Fluent - but here goes:
I have the following mappings
As you can probably spot - this is not going to work because the keys on the child table do not match the parent table and so the error will be that the number of fields on the foreign key contract don't match. However, I cannot change the underlying tables (and the relationship is a valid one). Is there a way around this in fluent nhibernate so I can somehow ignore the expected join on both composite fields and only join on the one which matches (i.e field_one?) Hibernate expects that field one and field two are present on both mappings.
public ParentMap()
{
Table("dbo.SOMEPARENT");
OptimisticLock.None();
LazyLoad();
CompositeId()
.KeyReference(x => x.FieldOne, x => x.Access.CamelCaseField(Prefix.Underscore), "field_one")
.KeyReference(x => x.FieldTwo, x => x.Access.CamelCaseField(Prefix.Underscore), "field_two");
HasMany(x => x.ChildData)
.Access.CamelCaseField(Prefix.Underscore)
.Cascade.AllDeleteOrphan()
.KeyColumns.Add("field_one")
.NotFound.Ignore();
}
public ChildDataMap()
{
Table("dbo.SOMECHILD");
OptimisticLock.None();
LazyLoad();
CompositeId()
.KeyProperty(x => x.FieldOne, x => x.Access.CamelCaseField(Prefix.Underscore).ColumnName("field_one"))
.KeyProperty(x => x.FieldTwo, x => x.Access.CamelCaseField(Prefix.Underscore).ColumnName("field_two"))
.KeyProperty(x => x.FieldThree, x => x.Access.CamelCaseField(Prefix.Underscore).ColumnName("field_three"))
.KeyProperty(x => x.FieldFour, x => x.Access.CamelCaseField(Prefix.Underscore).ColumnName("field_four"));
Map(x=>x.DontExecTrigger).Column("dont_exec_trigger").Access.CamelCaseField(Prefix.Underscore);
Map(x=>x.DateField).Column("date_field").Access.CamelCaseField(Prefix.Underscore);
Map(x=>x.DataField).Column("data_field").Access.CamelCaseField(Prefix.Underscore);
References(x => x.Parent)
.Access.CamelCaseField(Prefix.Underscore)
.Cascade.All()
.Fetch.Select()
.Columns("field_one")
.NotFound.Ignore()
.Not.LazyLoad();
}
From a purely database point of view, if a ChildDataMap FieldOne value always appears in ParentMap FieldOne and FieldOne is unique in ParentMap then there is a foreign key from the former to the latter. But also it means FieldOne is a candidate key of (unique in) ParentMap.
You should declare the FK and UNIQUE database constraints. You say you can't change the table but if the constraint is valid then it is not going to affect any useres of it. That ought to allow you to declare that ChildDataMap FirstOne References ParentMap FirstOne. The two-column set can still be declared PK (assuming it is). But if ParentMap FieldTwo is also unique, it should be declared UNIQUE also and so become available as one-column FK target.
Maybe the UNIQUE constraint and/or FK are already declared. Maybe you should just be declaring the corresponding unique property for FirstOne in ParentMap. The KeyColumns.Add ought rely on its being there and allow you to declare the References in ChildDataMap. But I guess that's where your code is not valid.
If Hibernate doesn't automatically join on same-named fields then you could just not declare the References and do your own join on the one field to get a set of references of which of course there will be only one element.
It's not clear what you mean by "you can't change the tables" (does that include, you can't have valid constraints added?) or "the relationship is a valid one" (does that mean, FieldOne in Parent is unique?). It would also help if you posted all the relevant code: namely the table delarations including constraints.
If you can have a new table defined, you can add StricterParentMap with the added constraints and have ParentMap declared as a view of it. This wouldn't affect others' use of it and might not count as "can't change".

NHibernate not inserting child entities in one-to-many

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.
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!
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.

Mapping two columns with the same name in nhibernate

I've come across a case, we're I've a column mapped twice (un-beknown to us..), and now updates are throwing the "Parameter +1 doesn't exist error".
Is there any suitable way we can achieve the following mapping?
(Please note, this is an inherited database...)
References(x => x.Matter).Columns(new[] { "c_client", "c_matter" }).NotFound.Ignore();
References(x => x.Client).Column("c_client");
An option for you could be to mark the Client column as read only.
References(x => x.Matter).Columns(new[] { "c_client", "c_matter" }).NotFound.Ignore();
References(x => x.Client).Column("c_client").ReadOnly();
This should make it so NHiberante does not try to update it
This is an invalid mapping. You can't use the same column twice.
My suggestion is that you map c_matter and c_client as scalar properties and use queries to retrieve the corresponding matters and clients.

NHibernate: Problem trying to save an entity containing collections

I need some help.
I'm just starting out with NHibernate and I'm using Fluent for mappings. Everything seemed to work fine until today.
Here is the story:
I have two tables in my db: Store and WorkDay
The first table contains info about the store, and the WorkDay table contains info about the days of week and start/end time when the store is open.
Store contains a Guid StoreID PK column that is referenced in the WorkDay table.
So I have a mapping file for Store where I have a HasMany association with the WorkDay table, and a corresponding POCO for Store.
Now, when I fill in all the necessary data and try to persist it to database, I get an exception telling me that the insert into table WorkDay failed because the StoreID had null value and the table constraint doesn't allow nulls for that column (which is, of course, expected behavior).
I understand the reason for this exception, but I don't know how to solve it.
The reason why the insert fails is because the StoreID gets generated upon insert, but the [b]WorkDay[/b] collection gets saved first, in the time when the StoreID hasn't yet been generated!
So, how do I force NHibernate to generate this ID to pass it to dependent tables? Or is there another solution for this?
Thank you!
Here's the code for StoreMap
public class StoreMap : ClassMap<Store> {
public StoreMap() {
Id(x => x.StoreID)
.GeneratedBy.GuidComb();
Map(x => x.City);
Map(x => x.Description);
Map(x => x.Email);
Map(x => x.Fax);
Map(x => x.ImageData).CustomType("BinaryBlob");
Map(x => x.ImageMimeType);
Map(x => x.Name);
Map(x => x.Phone);
Map(x => x.Street);
Map(x => x.Zip);
HasMany(x => x.WorkDays)
.Inverse().KeyColumn("StoreID").ForeignKeyCascadeOnDelete()
.Cascade.All();
}
}
and this is for the WorkDayMap
public class WorkDayMap : ClassMap<WorkDay>{
public WorkDayMap() {
Id(x => x.WorkDayID)
.GeneratedBy.Identity();
Map(x => x.TimeOpen);
Map(x => x.TimeClose);
References(x => x.Store).Column("StoreID");
References(x => x.Day).Column("DayID");
}
}
NHibernate shouldn't insert the WorkDay first, so there must be an error in your code. Make sure you do all of the following:
Add all WorkDay objects to the WorkDays collection.
Set the Store property on all WorkDay objects to the parent object.
Call session.Save() for the Store but not for the WorkDay objects.
edit: You should also note that ForeignKeyCascadeOnDelete() won't change anything at runtime. This is just an attribute for the hbm2ddl tool. If you want NHibernate to delete removed entries, use Cascade.AllDeleteOrphan().
It probably inserts the Workday before the Store because the first has an identity generator. This forces NH to execute an INSERT statement to generate the ID. guid.comb is generated in memory, NH doesn't need the database.
NH tries to access the db at the latest possible point in time, to avoid unnecessary updates and to make use of batches. Workday is inserted when you call session.Save, Store is inserted when it flushes the session next time (eg. on commit).
You shouldn't use the identity generator (unless you are forced to use it). It is bad for performance anyway.
If it still doesn't work, you probably need to remove the not-null constraint on the foreign key. NH can't resolve it every time. There is some smart algorithm which is also able to cope with recursive references. But there are sometimes cases where it sets a foreign key to null and updates it later even if there would be a solution to avoid it.

NHibernate Issuing Unwanted Orphaning Statements

Imagine that I have a Parent/Child relationship managed by NHibernate.
I'm receiving a Parent object from an MVC postback that edits its properties; I want to save just the parent to the database without having to load the children from the database.
At the time of the save, Parent has a Children property that is null (because it hasn't been loaded; there are, however, valid Children in the database for that parent).
When I save a modified Parent (ID=100), NHibernate is issuing a "SET Child.ParentId = NULL WHERE Child.ParentId = 100" statement. I don't want this to happen because there could be valid children. I shouldn't have to load them from the database before the save just to prevent them from being orphaned.
The fluent mappings look like this (true entity names genericized for this post):
public ParentMapping()
{
Table("Parent");
Id(x => x.Id).Column("Id").GeneratedBy.Identity();
Map(x => x.ParentProperty1).Column("ParentProperty1").Not.Nullable();
HasMany(x => x.Children).Cascade.None();
}
public ChildMapping()
{
Table("Children");
Id(x => x.Id).Column("Id").GeneratedBy.Identity();
Map(x => x.ChildProperty1).Column("ChildProperty1").Not.Nullable();
References(x => x.Parent).Column("Parent_Id").Not.Nullable().Fetch.Select();
}
To summarize, I want to save an updated Parent instance that was retrieved from an earlier ISession (and passed to a browser and back through MVC model minding); its Children property is null, but in reality it's got plenty of children in the database. I don't want NHibernate to issue any modifying statements to the Children table at all.
I've experimented with Cascade.None() and LazyLoad() in the hopes that this nudges NHibernate to behave differently, but no luck.
Any insight would be appreciated. Thanks!
Jeff
You must specify Inverse() on the has many to tell nhibernate not to worry about this side of the collection