开发者

NHibernate - No Inverse on One-to-one

my application has 2 entities called Event and Transaction. An Event may or may not have a transacti开发者_StackOverflowon but can only have 1 Transaction. I thought the best way to map this was with a HasOne mapping. So far everything is fine but i want to make sure that when you delete an Event it won't delete it if has a Transaction.

Normally on a HasMany relationship i would just set an Inverse and change Cascade to None. While Cascade exists, Inverse doesn't and the event deletes regardless of whether it has a Transaction or not.

I'd appreciate it if someone could show me the correct way of doing this. Thanks


You could always create your own custom delete behaviour using a DeleteEventListener:

public class DeleteEventListener : DefaultDeleteEventListener
  {
    protected override void DeleteEntity(IEventSource session, object entity, EntityEntry entityEntry, bool isCascadeDeleteEnabled, IEntityPersister persister, ISet transientEntities)
    {
      Event event = entity as Event;
      if (event != null && event.Transaction != null) throw new Exception("You can't delete this Event! Look! It has a Transaction!");
      CascadeBeforeDelete(session, persister, entity, entityEntry, transientEntities);
      CascadeAfterDelete(session, persister, entity, transientEntities);
    }
  }

This DeleteEventListener would then need to be registered as part of your NHibernate setup configuration. Within the session factory element:

<event type="delete">
<listener class="myNamespaces.DeleteEventListener, myAssembly" />
</event> 

I haven't tested this particular code but I have similar code in my app so I can help out if you get stuck.


one-to-one means that there is no foreign key, but a synchronized primary key. it means, that the primary key of the Event is taken from Transaction.

It does not have anything to do with cascades.

Inverse indicates that a relation shares the foreign key with another relation. For instance, if there is a list (one-to-many), it contains the same information as the inverse reference from the item in the list to its container. So it does not need to store this information twice in the database, it is marked "inverse"

In most cases, many-to-one is the correct choice. AFAIK, In fluent it is called "References".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜