views:

32

answers:

1

let's say i have the following entities:

public class Order
{
  public int OrderID {get;set;};
  public int Version {get;set;};

public IList<OrderDetail> Details {get;set;}
}

public class OrderDetail
{
  public int OrderDetailID {get;set;}
  /// Some other properties
}

when i want to delete the entity like this:

 Order order = new Order { OrderID = 9, Version =1 };
 ITransaction tr = Session.BeginTransaction();
 Session.Delete(order);
 tr.Commit();

well the order is deleted, but the details is still there with (OrderID) foreign key set to null ? but when i try to delete it like this, it worked as expected:

 Order order = Session.Get<Order>(9);
 ITransaction tr = Session.BeginTransaction();
 Session.Delete(order);
 tr.Commit();

why should i have to get the entire entity from database, in order to delete it?

BTW: i tried to create an instance of Order and fill the information and details information manually, it also worked???

can't i just do it as simple as possible ?

+1  A: 

First, you are going against the principles of NHibernate with this approach. See Ayende's (he's one of the main developers behind it) response to this question in this thread)

If you are using NHibernate versioning (it looks like you are because of the presence of that Version property) then you will have to get the Order item from the database anyway because it shouldn't let you delete without the correct version number being provided and how would you know it without checking the database?

The idea below may work:

Create the reference to the Order entity the "NHibernate" way. The Correct way to reference a persisted entity without making a call to the database is to use the Session.Load function. This will return a proxy object of the entity in question which can hydrate itself from the database if needed. You would need to replace this line:

Order order = new Order { OrderID = 9, Version =1 };

with

Order order = Session.Load<Order>(9);

You will have to check with a profiler or logger to see if the Order was actually rehydrated from the database in this instance (which to be honest I think it will).

Michael Gattuso
@Michael, considering the versioning: I'm aware of that i need to provide the correct version, and it is not a problem. because i already holding the id and the version of the entity. but even that, nhibernate consider it not enough. i tried the Load and as you said it isn't rehydrated from the database . but when you call the delete, it first make a select statement, and then delete one. well, if this is the only solution, so i will use it. but still can't understand why just it make a delete statement and use the Id and version as criterion ??
Nour Sabouny