NHibernate throwing cast exceptions with components - nhibernate

I'm using NHibernate, I have a one to many relationship with a cascade on delete. Mappings below.
<class name="Photo" table="photos">
<id name="RoomId" column="room_id">
<generator class="guid"/>
</id>
// omitted for brevity
<component name="Data" class="PhotoData" lazy="true">
<property name="Mime" column="mime"/>
<property name="Data" column="data" length="2048000"/>
</component>
</class>
<class name="Room" table="rooms">
// omitted for brevity
<bag name="Photos" lazy="false" fetch="join" cascade="delete" inverse="true">
<key>
<column name="room_id"/>
</key>
<one-to-many class="Photo"/>
</bag>
</class>
When I attempt delete a room, I get the following exception
Unable to cast object of type 'System.Object' to type 'PhotoData'
If I remove the component from my photo mapping I can delete the room and all the photos without a problem.
Any suggestions?
UPDATE: As per comment from #nemesv
The stack trace is below, there is no inner exception.
at (Object , GetterCallback )
at NHibernate.Bytecode.Lightweight.AccessOptimizer.GetPropertyValues(Object target) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Bytecode\Lightweight\AccessOptimizer.cs:line 27
at NHibernate.Tuple.Component.PocoComponentTuplizer.GetPropertyValues(Object component) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Tuple\Component\PocoComponentTuplizer.cs:line 68
at NHibernate.Type.ComponentType.GetPropertyValues(Object component, ISessionImplementor session) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Type\ComponentType.cs:line 291
at NHibernate.Engine.ForeignKeys.Nullifier.NullifyTransientReferences(Object value, IType type) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\ForeignKeys.cs:line 74
at NHibernate.Engine.ForeignKeys.Nullifier.NullifyTransientReferences(Object[] values, IType[] types) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\ForeignKeys.cs:line 38
at NHibernate.Event.Default.DefaultDeleteEventListener.DeleteEntity(IEventSource session, Object entity, EntityEntry entityEntry, Boolean isCascadeDeleteEnabled, IEntityPersister persister, ISet transientEntities) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Event\Default\DefaultDeleteEventListener.cs:line 204
at NHibernate.Event.Default.DefaultDeleteEventListener.OnDelete(DeleteEvent event, ISet transientEntities) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Event\Default\DefaultDeleteEventListener.cs:line 111
at NHibernate.Impl.SessionImpl.FireDelete(DeleteEvent event, ISet transientEntities) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\SessionImpl.cs:line 2478
at NHibernate.Impl.SessionImpl.Delete(String entityName, Object child, Boolean isCascadeDeleteEnabled, ISet transientEntities) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\SessionImpl.cs:line 975
at NHibernate.Engine.CascadingAction.DeleteCascadingAction.Cascade(IEventSource session, Object child, String entityName, Object anything, Boolean isCascadeDeleteEnabled) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\CascadingAction.cs:line 158
at NHibernate.Engine.Cascade.CascadeToOne(Object parent, Object child, IType type, CascadeStyle style, Object anything, Boolean isCascadeDeleteEnabled) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\Cascade.cs:line 216
at NHibernate.Engine.Cascade.CascadeAssociation(Object parent, Object child, IType type, CascadeStyle style, Object anything, Boolean isCascadeDeleteEnabled) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\Cascade.cs:line 181
at NHibernate.Engine.Cascade.CascadeProperty(Object parent, Object child, IType type, CascadeStyle style, Object anything, Boolean isCascadeDeleteEnabled) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\Cascade.cs:line 148
at NHibernate.Engine.Cascade.CascadeCollectionElements(Object parent, Object child, CollectionType collectionType, CascadeStyle style, IType elemType, Object anything, Boolean isCascadeDeleteEnabled) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\Cascade.cs:line 240
at NHibernate.Engine.Cascade.CascadeCollection(Object parent, Object child, CascadeStyle style, Object anything, CollectionType type) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\Cascade.cs:line 201
at NHibernate.Engine.Cascade.CascadeAssociation(Object parent, Object child, IType type, CascadeStyle style, Object anything, Boolean isCascadeDeleteEnabled) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\Cascade.cs:line 185
at NHibernate.Engine.Cascade.CascadeProperty(Object parent, Object child, IType type, CascadeStyle style, Object anything, Boolean isCascadeDeleteEnabled) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\Cascade.cs:line 148
at NHibernate.Engine.Cascade.CascadeOn(IEntityPersister persister, Object parent, Object anything) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Engine\Cascade.cs:line 126
at NHibernate.Event.Default.DefaultDeleteEventListener.CascadeBeforeDelete(IEventSource session, IEntityPersister persister, Object entity, EntityEntry entityEntry, ISet transientEntities) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Event\Default\DefaultDeleteEventListener.cs:line 253
at NHibernate.Event.Default.DefaultDeleteEventListener.DeleteEntity(IEventSource session, Object entity, EntityEntry entityEntry, Boolean isCascadeDeleteEnabled, IEntityPersister persister, ISet transientEntities) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Event\Default\DefaultDeleteEventListener.cs:line 202
at NHibernate.Event.Default.DefaultDeleteEventListener.OnDelete(DeleteEvent event, ISet transientEntities) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Event\Default\DefaultDeleteEventListener.cs:line 111
at NHibernate.Event.Default.DefaultDeleteEventListener.OnDelete(DeleteEvent event) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Event\Default\DefaultDeleteEventListener.cs:line 30
at NHibernate.Impl.SessionImpl.FireDelete(DeleteEvent event) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\SessionImpl.cs:line 2465
at NHibernate.Impl.SessionImpl.Delete(Object obj) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\SessionImpl.cs:line 508
at DataAccess.Respository`1.<>c__DisplayClass7.<Delete>b__6(ISession s) in D:\svn\flatsharespa\DataAccess\Respository.cs:line 4

Related

Ajax POST to MVC4 with special characters '&#' does not work [duplicate]

This question already has answers here:
A potentially dangerous Request.Form value was detected from the client - ASP.NET MVC
(5 answers)
Closed 9 years ago.
Ajax POST data that contains '&#' characters causes MVC4 controller fails to decode. Following were my tests;
POST data contains 'MYNAMEIS&#XYZ' , result ERROR
POST data contains 'MYNAMEIS& #XYZ' (note the space), result SUCCESS
POST data contains 'MYNAMEIS#&XYZ' (note the order of special characters), result
SUCCESS
POST data contains 'Q&^%AA#####$%' (note bunch of special
characters), result SUCCESS
It doesn't work when # comes right after & in the POST request. I've verified that request encoding is set to UTF-8 in web.config, _layout.cshtml . But still no luck.
Please help how to resolve this issue.
Stack Trace from the exception;
<!--
[HttpRequestValidationException]: A potentially dangerous Request.Form value was detected from the client (Name="&#").
at System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection)
at System.Web.HttpRequest.<>c__DisplayClass5.<ValidateHttpValueCollection>b__3(String key, String value)
at System.Web.HttpValueCollection.EnsureKeyValidated(String key)
at System.Web.HttpValueCollection.GetValues(String name)
at System.Web.Mvc.NameValueCollectionValueProvider.ValueProviderResultPlaceholder.GetResultFromCollection(String key, NameValueCollection collection, CultureInfo culture)
at System.Web.Mvc.NameValueCollectionValueProvider.ValueProviderResultPlaceholder.<>c__DisplayClass8.<.ctor>b__4()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Web.Mvc.NameValueCollectionValueProvider.GetValue(String key, Boolean skipValidation)
at System.Web.Mvc.ValueProviderCollection.GetValueFromProvider(IValueProvider provider, String key, Boolean skipValidation)
at System.Web.Mvc.ValueProviderCollection.<>c__DisplayClass9.<GetValue>b__4(IValueProvider provider)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at System.Web.Mvc.ValueProviderCollection.GetValue(String key, Boolean skipValidation)
at System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
at System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
at System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model)
at System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
Use the ValidateInput(false) attribute.
You can also encode the &# characters and then decode them on the server.

Deleting an entity with reference to self

I have a class for messages in a message thread. Each message has a reference to the root message of the thread:
<class name="Message">
...
<many-to-one name="Root" not-null="true"/>
</class>
<joined-subclass name="Comment" extends="Message">
...
</joined-subclass>
Now I want to delete a comment. This works fine for all but the root comments. Deleting a root comment, where the Root property points to the message itself, yields the following exception:
NHibernate.PropertyValueException : not-null property references a null or transient value
at NHibernate.Engine.Nullability.CheckNullability(Object[] values, IEntityPersister persister, Boolean isUpdate)
at NHibernate.Event.Default.DefaultDeleteEventListener.DeleteEntity(IEventSource session, Object entity, EntityEntry entityEntry, Boolean isCascadeDeleteEnabled, IEntityPersister persister, ISet transientEntities)
at NHibernate.Event.Default.DefaultDeleteEventListener.OnDelete(DeleteEvent event, ISet transientEntities)
at NHibernate.Impl.SessionImpl.FireDelete(DeleteEvent event)
at NHibernate.Impl.SessionImpl.Delete(Object obj)
This error appeared first when I upgraded from NHibernate 3.0 to 3.3. When I remove the not-null constraint, I get an SQL exception indicating that the respective column constraint was violated. Now I wonder why NHibernate actually tries to save a to be deleted entity. Does anyone have an idea how to deal with this?
not-null should be set to false, because, at least one of these entries will require it: the first "father".

NHibernate gets crashed by a magic string

Here is my trivial program:
public class Entity
{
public virtual long Id { get; set; }
public virtual string Payload { get; set; }
}
class Program
{
static void Main( string[] args )
{
var config = new Configuration().Configure();
var sessionFactory = config.BuildSessionFactory();
using ( var session = sessionFactory.OpenSession() )
{
var entity = new Entity { Payload = "'))" };
session.Save( entity );
}
}
}
As long as Payload property is assigned any innocent string such as 'Hi there' everything works as expected. However this particular magic string ')) makes NHibernate throw an exception: 'Index was out of range. Must be non-negative and less than the size of the collection' when it tries to save the entity.
I wonder why NHibernate cares of the parameter content. It really shouldn't.
Or maybe something is very wrong with this sample?
NHibernate version is 2.1
SQL script:
create table tblEntity
(
EntityId BIGINT NOT NULL IDENTITY PRIMARY KEY
,Payload VARCHAR(10) NOT NULL
)
Mapping:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="MyNamespace.Entity, MyAssembly"
table="tblEntity">
<id name="Id" column="EntityId" unsaved-value="0">
<generator class="identity"/>
</id>
<property name="Payload"/>
</class>
</hibernate-mapping>
NHibernate settings:
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string_name">Main</property>
<property name="connection.isolation">ReadCommitted</property>
<property name="default_schema">dbo</property>
<property name="format_sql">true</property>
<property name="query.substitutions">true=1;false=0</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<mapping assembly="MyAssembly"/>
</session-factory>
</hibernate-configuration>
Nothing special as you can see, not too much room for mistakes.
Stack Trace
System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
System.ThrowHelper.ThrowArgumentOutOfRangeException()
System.Collections.Generic.List`1.get_Item(Int32 index)
NHibernate.AdoNet.Util.BasicFormatter.FormatProcess.CloseParen()
NHibernate.AdoNet.Util.BasicFormatter.FormatProcess.Perform()
NHibernate.AdoNet.Util.BasicFormatter.Format(String source)
NHibernate.AdoNet.Util.SqlStatementLogger.LogCommand(String message, IDbCommand command, FormatStyle style)
NHibernate.AdoNet.Util.SqlStatementLogger.LogCommand(IDbCommand command, FormatStyle style)
NHibernate.AdoNet.AbstractBatcher.LogCommand(IDbCommand command)
NHibernate.AdoNet.AbstractBatcher.Prepare(IDbCommand cmd)
NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
NHibernate.Id.IdentityGenerator.InsertSelectDelegate.ExecuteAndExtract(IDbCommand insert, ISessionImplementor session)
NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder)
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Boolean[] notNull, SqlCommandInfo sql, Object obj, ISessionImplementor session)
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Object obj, ISessionImplementor session)
NHibernate.Action.EntityIdentityInsertAction.Execute()
NHibernate.Engine.ActionQueue.Execute(IExecutable executable)
NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object entity, EntityKey key, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
NHibernate.Event.Default.AbstractSaveEventListener.PerformSave(Object entity, Object id, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
NHibernate.Event.Default.DefaultSaveEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event)
NHibernate.Event.Default.DefaultSaveEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent event)
NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
NHibernate.Impl.SessionImpl.FireSave(SaveOrUpdateEvent event)
NHibernate.Impl.SessionImpl.Save(Object obj)
I have looked up the changes made to
src/NHibernate/AdoNet/Util/BasicFormatter.cs
there was an issue in NH 2.1 that caused this behavior, this was fixed in 2.1.1.GA.
Bugtracker: NH-1992
Changeset on github: Commit
I believe it might be a bug with NHibernate. When a command is logged (because you have show_sql set to true) it will write out your command and it will look something like this:
insert into tblEntity (Payload) VALUES(#p0); #p0 = ''(('
The logger then tries to tokenize the string and gets confused by the parentheses. Try submitting a bug to the NHibernate JIRA. In the meantime you can try turning off show_sql
I am not familiar with NHibernate, however what you are describing looks as if it might be the result of inadvertant SQL Injection Hopefully the linked wiki page might help.

FluentNhibernate Mapping Using References Index Out of Range When Adding new Object

I am trying to map a parent child relationship between a Person object and a Organization object in FluentNHibernate using References in the mapping file like this:
References(x => x.Organization);
The relationship is a Person object contains a OrganizationId column that corresponds to a record in the Organization table with the corresponding OrganizationId. Different Person records can belong to the same Organization.
When I retrieve a Person object it works properly. Person.Organization is populated. I can save a Person object and it works properly. However, when I attempt to add a new Person object I get a Index Out of Range exception from NHibernate. The exception occurs when calling session.SaveOrUpdate(person). I've tried changing the mapping to:
References(x => x.Organization).Cascade.None()
Still get the same error. I can't figure out what is causing the exception. The full exception is this:
System.IndexOutOfRangeException : Invalid index 22 for this SqlParameterCollection with Count=22.
at System.Data.SqlClient.SqlParameterCollection.RangeCheck(Int32 index)
at System.Data.SqlClient.SqlParameterCollection.GetParameter(Int32 index)
at System.Data.Common.DbParameterCollection.System.Collections.IList.get_Item(Int32 index)
at NHibernate.Type.NullableType.NullSafeSet(IDbCommand cmd, Object value, Int32 index)
at NHibernate.Type.ManyToOneType.NullSafeSet(IDbCommand st, Object value, Int32 index, Boolean[] settable, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object id, Object[] fields, Object rowId, Boolean[] includeProperty, Boolean[][] includeColumns, Int32 table, IDbCommand statement, ISessionImplementor session, Int32 index)
at NHibernate.Persister.Entity.AbstractEntityPersister.GeneratedIdentifierBinder.BindValues(IDbCommand ps)
at NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder)
at NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Boolean[] notNull, SqlCommandInfo sql, Object obj, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[] fields, Object obj, ISessionImplementor session)
at NHibernate.Action.EntityIdentityInsertAction.Execute()
at NHibernate.Engine.ActionQueue.Execute(IExecutable executable)
at NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object entity, EntityKey key, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.FireSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.SaveOrUpdate(Object obj)
First of all the exception occurs because you map the same column twice in your class and that is not allowed.
check this
IndexOutOfRangeException Deep in the bowels of NHibernate
Secondly (and according to your latest comment) having an OrganizationId and an Organization property in your Person class is sort-of going against the grain. You don't need it. You can access it via per1.Organization.Id
If you already have an Organization in your db (say Id=5) and you map the Organization class to the Person class using the OrganizationId foreign key, then when you code
Organization theOrganizationWithId5 = nhSession.Get<Organization>(5);
per1.Organization = theOrganizationWithId5;
nhSession.Save(per1);
NHibernate will just set the value 5 on the OrganizationId column in your Person table.
You will not be populating Organization.

IIS7 + NHibernate: Illegal operation attempted on a registry key that has been marked for deletion

We have an asp.net MVC app using Fluent Nhibernate running on top of IIS7 & Windows Sever 2008. Frequently (although so far we have yet to consistently reproduce it) after a build we get a yellow screen of death with this exception:
[COMException (0x800703fa): Illegal operation attempted on a registry key that has been marked for deletion. (Exception from HRESULT: 0x800703FA)]
System.Reflection.Assembly._nDefineDynamicModule(Assembly containingAssembly, Boolean emitSymbolInfo, String filename, StackCrawlMark& stackMark) +0
System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternalNoLock(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark) +381
System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternal(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark) +105
System.Reflection.Emit.AssemblyBuilder.DefineDynamicModule(String name, Boolean emitSymbolInfo) +83
Castle.DynamicProxy.ModuleScope.CreateModule(Boolean signStrongName) +206
Castle.DynamicProxy.ModuleScope.ObtainDynamicModuleWithWeakName() +63
Castle.DynamicProxy.Generators.Emitters.ClassEmitter.CreateTypeBuilder(ModuleScope modulescope, String name, Type baseType, Type[] interfaces, TypeAttributes flags, Boolean forceUnsigned) +78
Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, Type[] interfaces, TypeAttributes flags, Boolean forceUnsigned) +69
Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, Type[] interfaces) +36
Castle.DynamicProxy.Generators.BaseProxyGenerator.BuildClassEmitter(String typeName, Type parentType, Type[] interfaces) +140
Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateCode(Type[] interfaces, ProxyGenerationOptions options) +648
Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors) +139
Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, IInterceptor[] interceptors) +39
NHibernate.ByteCode.Castle.ProxyFactory.GetProxy(Object id, ISessionImplementor session) +416
[HibernateException: Creating a proxy instance failed]
NHibernate.ByteCode.Castle.ProxyFactory.GetProxy(Object id, ISessionImplementor session) +642
NHibernate.Tuple.Entity.AbstractEntityTuplizer.CreateProxy(Object id, ISessionImplementor session) +49
NHibernate.Persister.Entity.AbstractEntityPersister.CreateProxy(Object id, ISessionImplementor session) +102
NHibernate.Event.Default.DefaultLoadEventListener.CreateProxyIfNecessary(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options, IPersistenceContext persistenceContext) +255
NHibernate.Event.Default.DefaultLoadEventListener.ProxyOrLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +400
NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) +923
NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) +169
NHibernate.Impl.SessionImpl.InternalLoad(String entityName, Object id, Boolean eager, Boolean isNullable) +310
NHibernate.Type.EntityType.ResolveIdentifier(Object id, ISessionImplementor session) +211
NHibernate.Engine.TwoPhaseLoad.InitializeEntity(Object entity, Boolean readOnly, ISessionImplementor session, PreLoadEvent preLoadEvent, PostLoadEvent postLoadEvent) +527
NHibernate.Loader.Loader.InitializeEntitiesAndCollections(IList hydratedObjects, Object resultSetId, ISessionImplementor session, Boolean readOnly) +544
NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +1158
NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +105
NHibernate.Loader.Loader.LoadEntity(ISessionImplementor session, Object id, IType identifierType, Object optionalObject, String optionalEntityName, Object optionalIdentifier, IEntityPersister persister) +472
NHibernate.Loader.Entity.AbstractEntityLoader.Load(ISessionImplementor session, Object id, Object optionalObject, Object optionalId) +77
NHibernate.Loader.Entity.AbstractEntityLoader.Load(Object id, Object optionalObject, ISessionImplementor session) +30
NHibernate.Persister.Entity.AbstractEntityPersister.Load(Object id, Object optionalObject, LockMode lockMode, ISessionImplementor session) +182
NHibernate.Event.Default.DefaultLoadEventListener.LoadFromDatasource(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +174
NHibernate.Event.Default.DefaultLoadEventListener.Load(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +194
NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) +923
NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) +169
NHibernate.Impl.SessionImpl.Get(String entityName, Object id) +191
NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id) +139
NHibernate.Impl.SessionImpl.Get(Object id) +136
Huddle.DataAccess.Persistence.Repository`1.FindById(Int32 id) +281
Huddle.WebSite.Global.GetWorkspace() +241
Huddle.WebSite.Global.Application_BeginRequest(Object sender, EventArgs e) +437
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171
It seems a few other people have found the same problem although no one seems to have a solution, any ideas?
This sounds like something I've seen with COM+ and MSMQ on Windows 2008. What happens is that Windows 2008 unloads the user registry hive as soon as the user is logged off, regardless of any remaining open handles. You should see entries in the event log that the hive was unloaded with processes still using it.
There is a GPO that can be set to prevent this from happening (DisableForceUnload)
More information here:
http://blogs.msdn.com/distributedservices/archive/2009/11/06/a-com-server-application-may-stop-working-on-windows-server-2008.aspx
This looks like a bug in the .NET framework itself.
Notice that the innermost method being called, does not specify it can throw a ComException.
I would suggest updating to the most recent version of Castle Dynamic Proxy (2.2 beta) to see if the problem persists.
If it does you may try using one of the other proxy providers.
And also report this issue to Microsoft Connect