开发者

Using nhibernate ,to delete entity with details cascade-delete-orphan,why do I have to get the entity with all details, in order to delete them too?

Let's say I have the following entities:

public class Order
{
  public开发者_如何学C 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 ?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜