NHibernate cascade delete from another entity collection - nhibernate

I have these classes:
public class User
{
public IList<Order> LastOrders { get; set;}
}
public class Order {}
Where LastOrders is many-to-many map.
How do I tell (Fluent) NHibernate to remove Order from LastOrders collections for all users when I delete an Order? Is it possible?
That is (db save/load code skipped)
user.LastOrders.Add(order);
Session.Delete(order);
Assert(!user.LastOrders.Contains(order));
Currently I do it manually (lookup for users, update collection, save) before deletion. Without this, NHibernate can't delete Order because it is referenced by users' LastOrders.

You can safely delete the Order if the collection mapping is set to ignore missing rows.
This will leave orphaned rows in the collection table which will be ignored by NHibernate. These can be cleaned up in some batch process.
HasManyToMany(x => x.LastOrders)
.NotFound.Ignore();
This will give you faster deletes then your current approach. The disadvantage is that your collection tables will be inconsistent with your model for a time.

Related

How can i delete the content of the table using fluentnhibernate?

I am using fluent nHibernate for my mappings as follow:
public class ContentTagMap: ClassMap<Employee>
{
public EmployeeMap()
{
Id(t => t.Id);
Map(t => t.Name);
HasManyToMany(t => t.Company);
}
}
public class CompanyMap: ClassMap<Company>
{
public HelpMap()
{
Id(h => h.Id);
Map(h => h.CompanyName).Length(6000);
Map(h => h.address).Length(6000);
HasManyToMany(h => h.Employee);
}
}
These mappings produce Employee Table ,Company Table and EmployeeToCompany Table
Employee Table
Id Name
1 John
2 MAX
Company Table
Id CompanyName address
1 HTC ABC
2 HTC2 India
EmployeeToCompany Table
Employee_Id Company_Id
1 1
2 1
How can I delete the employee with Id 1?
Unless I'm misunderstanding your question you should be asking:
How can i delete the content of the table using NHibernate?
Fluent NHibernate is only a tool to aid in the mapping of your entities. NHibernate is what you use to create, read, update and delete data. In any event:
9.5. Deleting persistent objects
ISession.Delete() will remove an object's state from the database. Of
course, your application might still hold a reference to it. So it's
best to think of Delete() as making a persistent instance transient.
From the NHibernate Documentation
You probably want to also define a Cascading style on your many to many relationship (HasManyToMany) in your mapping.
If you use Cascade.SaveUpdate in your many to many whenever you delete an entity on one side of the relationship it will delete that entity and any relationships. If you remove the association (ex. if you removed an Employee from a Company) it will only delete the relationship (EmployeeToCompany). This is what I've typically found to work in the case of many to many relationships.
Look at this article for more details on mapping and using a many to many relationship in Fluent NHibernate.
how to keep many to many relationships in sync with nhibernate?

NHibernate many-to-many and deleting an item

I've got a many-to-many association between Lists and ListItems: a List knows about its Items, but a ListItem doesn't know about the containing lists. The cascade is saveupdate.
So, whenever I'm trying to delete a ListItem entity, I'm getting an SQLException saying I'm breaking the referential integrity. NHibernate tries to delete my ListItem without deleting the corresponding row in the linking table. The question is, is it possible to instruct NHibernate to delete my ListItem without breaking the referential integrity?
In case I have to manually remove the item from all containing lists, how do I properly do that?
Thanks a lot for any advice.
ulu
You need to set the mapping on the child to inverse=true. From another thread:
When you call SaveOrUpdate NHibernate
first deletes all of the child
objects. Then, because neither
relationship is marked as inverse,
NHibernate also tries to set the
foreign key column in your child table
to null. Since the rows have already
been deleted, you receive the second
error. You need to set inverse=true on
one side of your relationship to fix
this. This is usually done on the one
(primary key or parent) side. If you
do not do this, NHibernate will make
the appropriate updates for each side
of the relationship.
public class StoreMap : ClassMap<Store>
{
public StoreMap()
{
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.Staff)
.Inverse() // Magic code!
.Cascade.All();
}
}

One to one self reference with Fluent NHibernate

Okay, I think I have a scenario I haven't seen elsewhere. I have a situation where I have an object type that needs to be able to be changed over time while retaining the history of the changes within the same table (as opposed to just in an audit table).
public class Item
{
public virtual int Id { get; set; }
public virtual ....
public virtual Item Replaces { get; set; }
public virtual Item ReplacedBy { get; set; }
}
I am stuck as to how to represent this in Fluent NHIbernate. In the database, I don't need both a Replaces and ReplacedBy field - I can get the info from just one of them. But I think I need both in my object for NHibernate to figure it out.
Currently, I have this, but it generates no database mappings at all:
mapping.HasOne(t => t.ReplacedBy).ForeignKey("Id").Class(typeof(Item));
As always, any thoughts greatly appreciated!
A HasOne or one-to-one relationship is a bit of a special relationship in NHibernate. It's (typically) an inferred relationship between two separate tables, whereby records that share a primary key value are associated. It's unlikely you'd be able to get a HasOne working for your situation. I have a post on my blog, I think you mean a many-to-one, sir, which goes into some of the misconceptions of HasOne relationships.
Instead you should look at using References, which is a many-to-one relationship, and does support self referential relationships.

Restricting deletion with NHibernate

I'm using NHibernate (fluent) to access an old third-party database with a bunch of tables, that are not related in any explicit way. That is a child tables does have parentID columns which contains the primary key of the parent table, but there are no foreign key relations ensuring these relations. Ideally I would like to add some foreign keys, but cannot touch the database schema.
My application works fine, but I would really like impose a referential integrity rule that would prohibit deletion of parent objects if they have children, e.i. something similar 'ON DELETE RESTRICT' but maintained by NHibernate.
Any ideas on how to approach this would be appreciated. Should I look into the OnDelete() method on the IInterceptor interface, or are there other ways to solve this?
Of course any solution will come with a performance penalty, but I can live with that.
I can't think of a way to do this in NHibernate because it would require that NHibernate have some knowledge of the relationships. I would handle this in code using the sepecification pattern. For example (using a Company object with links to Employee objects):
public class CanDeleteCompanySpecification
{
bool IsSatisfiedBy(Company candidate)
{
// Check for related Employee records by loading collection
// or using COUNT(*).
// Return true if there are no related records and the Company can be deleted.
// Hope that no linked Employee records are created before the delete commits.
}
}

How to find if a referenced object can be deleted?

I have an object called "Customer" which will be used in the other tables as foreign keys.
The problem is that I want to know if a "Customer" can be deleted (ie, it is not being referenced in any other tables).
Is this possible with Nhibernate?
What you are asking is to find the existence of the Customer PK value in the referenced tables FK column.
There are many ways you can go about this:
as kgiannakakis noted, try to do the delete and if an exception is thrown rollback. Effective but ugly and not useful. This also requires that you have set a CASCADE="RESTRICT" in your database. This solution has the drawback that you have to try to delete the object to find out that you can't
Map the entities that reference Customer as collections and then for each collection if their Count > 0 then do not allow the delete. This is good because this is safe against schema changes as long as the mapping is complete. It is also a bad solution because additional selects will have to be made.
Have a method that performs a query like bool IsReferenced(Customer cust). Good because you can have a single query which you will use when you want. Not so good because it may be susceptible to errors due to schema and/or domain changes (depending on the type of query you will do: sql/hql/criteria).
A computed property on the class it self with a mapping element like <property name="IsReferenced" type="long" formula="sql-query that sums the Customer id usage in the referenced tables" />. Good because its a fast solution (at least as fast as your DB is), no additional queries. Not so good because it is susceptible to schema changes so when you change your DB you mustn't forget to update this query.
crazy solution: create a schema bound view that makes the calculation. Make the query on it when you want. Good because its schema-bound and is less susceptible to schema changes, good because the query is quick, not-so-good because you still have to do an additional query (or you map this view's result on solution 4.)
2,3,4 are also good because you can also project this behavior to your UI (don't allow the delete)
Personally i would go for 4,3,5 with that preference
I want to know if a "Customer" can be deleted (ie, it is not being referenced in any other tables).
It is not really the database responsibility to determine if the Customer can be deleted. It is rather part of your business logic.
You are asking to check the referential integrity on the database.
It is ok in non OOP world.
But when dealing with objects (like you do) you better add the logic to your objects (objects have state and behavior; DB - only the state).
So, I would add a method to the Customer class to determine if it can be deleted or not. This way you can properly (unit) test the functionality.
For example, let's say we have a rule Customer can only be deleted if he has no orders and has not participated in forum.
Then you will have Customer object similar to this (simplest possible case):
public class Customer
{
public virtual ISet<Order> Orders { get; protected set; }
public virtual ISet<ForumPost> ForumPosts { get; protected set; }
public virtual bool CanBedeleted
{
get
{
return Orders.Count == 0 && ForumPosts.Count == 0
}
}
}
This is very clean and simple design that is easy to use, test and does not heavily relies on NHibernate or underlying database.
You can use it like this:
if (myCustomer.CanBeDeleted)
session.Delete(mycustomer)
In addition to that you can fine-tune NHibernate to delete related orders and other associations if required.
The note: of course the example above is just simplest possible illustrative solution. You might want to make such a rule part of the validation that should be enforced when deleting the object.
Thinking in entities and relations instead of tables and foreign keys, there are these different situations:
Customer has a one-to-many relation which builds a part of the customer, for instance his phone numbers. They should also be deleted by means of cascading.
Customer has a one-to-many or many-to-many relation which is not part of the customer, but they are known/reachable by the customer.
Some other entity has a relation to the Customer. It could also be an any-type (which is not a foreign key in the database). For instance orders of the customer. The orders are not known by the customer. This is the hardest case.
As far as I know, there is no direct solution from NHibernate. There is the meta-data API, which allows you to explore the mapping definitions at runtime. IMHO, this is the wrong way to do it.
In my opinion, it is the responsibility of the business logic to validate if an entity can be deleted or not. (Even if there are foreign keys and constraints which ensures integrity of the database, it is still business logic).
We implemented a service which is called before deletion of an entity. Other parts of the software register for certain types. They can veto against the deletion (eg. by throwing an exception).
For instance, the order system registers for deletion of customers. If a customer should be deleted, the order system searches for orders by this customer and throws if it found one.
It's not possible directly. Presumably your domain model includes Customer's related objects, such as Addresses, Orders, etc. You should use the specification pattern for this.
public class CustomerCanBeDeleted
{
public bool IsSatisfiedBy(Customer customer)
{
// Check that related objects are null and related collections are empty
// Plus any business logic that determines if a Customer can be deleted
}
}
Edited to add:
Perhaps the most straightforward method would be to create a stored procedure that performs this check and call it before deleting. You can access an IDbCommand from NHibernate (ISession.Connection.CreateCommand()) so that the call is database agnostic.
See also the responses to this question.
It might be worth looking at the cascade property, in particular all-delete-orphan in your hbm.xml files and this may take care of it for you.
See here, 16.3 - Cascading Lifecycle
A naive solution will be to use a transaction. Start a transaction and delete the object. An exception will inform you that the object can't be deleted. In any case, do a roll-back.
Map the entities that reference Customer as collections. Name each collection in your Customer class with a particular suffix.For example if your Customer entity has some Orders, name the Orders collection as below:
public virtual ISet<Order> Orders_NHBSet { get; set; } // add "_NHBSet" at the end
Now by using Reflection you can get all properties of Customer at run time and get those properties that their names ends with your defined suffix( In this case "_NHBSet" ) Then check each collection if they contain any element and if so avoid deleting customer.
public static void DeleteCustomer(Customer customer)
{
using (var session = sessions.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var listOfProperties =typeof(Customer).GetProperties();
foreach (var classProperty in listOfProperties )
{
if (classProperty.Name.EndsWith("_NHBSet"))
{
PropertyInfo myPropInfo = typeof(Customer).GetProperty(classProperty.Name);
dynamic Collection = myPropInfo.GetValue(customer, null);
if (Enumerable.FirstOrDefault(Collection) !=null)// Check if collection contains any element
{
MessageBox.Show("Customer Cannot be deleted");
return;
}
}
}
session.Delete(customer);
transaction.Commit();
}
}
}
The Advantage of this approach is that you don't have to change your code later if you add new collections to your customer class.And you don't need change your sql query as Jaguar suggested.
The only thing you must care about is to add the particular suffix to your newly added collections.