Add-Migration error: Object reference not set to an instance of an object - vb.net

I'm using code-first concept and just tried adding a new class to the Models folder in hope to create a new table in SQL server database. i've added
Public Overridable Property Diagnosis As DbSet(Of Diagnosis)
in the DBContext.vb.
Then in the package manager console, i entered Add-Migration Diagnosis. But below error comes out. Why is this? Can anyone help me out please?
Object reference not set to an instance of an object.
Full error in Package Manager Console:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Web.UI.ParseChildrenAttribute.GetHashCode()
at System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj)
at System.Linq.Set`1.InternalGetHashCode(TElement value)
at System.Linq.Set`1.Find(TElement value, Boolean add)
at System.Linq.Enumerable.<ExceptIterator>d__72`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.<GetAttributes>b__3(PropertyInfo pi)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(PropertyInfo propertyInfo)
at System.Data.Entity.ModelConfiguration.Conventions.PropertyAttributeConfigurationConvention`1.<.ctor>b__0(ConventionTypeConfiguration ec)
at System.Data.Entity.ModelConfiguration.Conventions.TypeConvention.ApplyCore(Type memberInfo, ModelConfiguration modelConfiguration)
at System.Data.Entity.ModelConfiguration.Conventions.TypeConventionBase.Apply(Type memberInfo, ModelConfiguration modelConfiguration)
at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.ApplyModelConfiguration(Type type, ModelConfiguration modelConfiguration)
at System.Data.Entity.ModelConfiguration.Conventions.Convention.ApplyModelConfiguration(Type type, ModelConfiguration modelConfiguration)
at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.ApplyModelConfiguration(Type type, ModelConfiguration modelConfiguration)
at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapComplexType(Type type, Boolean discoverNested)
at System.Data.Entity.ModelConfiguration.Mappers.PropertyMapper.MapPrimitiveOrComplexOrEnumProperty(PropertyInfo propertyInfo, Func`1 structuralTypeConfiguration, Boolean discoverComplexTypes)
at System.Data.Entity.ModelConfiguration.Mappers.PropertyMapper.MapIfNotNavigationProperty(PropertyInfo propertyInfo, EntityType entityType, Func`1 entityTypeConfiguration)
at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.<>c__DisplayClass14.<MapEntityType>b__e(PropertyMapper m, PropertyInfo p)
at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapStructuralElements[TStructuralTypeConfiguration](Type type, ICollection`1 annotations, Action`2 propertyMappingAction, Func`1 structuralTypeConfiguration)
at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapEntityType(Type type)
at System.Data.Entity.ModelConfiguration.Mappers.NavigationPropertyMapper.Map(PropertyInfo propertyInfo, EntityType entityType, Func`1 entityTypeConfiguration)
at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapEntityType(Type type)
at System.Data.Entity.DbModelBuilder.MapTypes(EdmModel model)
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.LazyInternalContext.get_ModelBeingInitialized()
at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
at System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter w)
at System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action`1 writeXml)
at System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext context)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Scaffold(String migrationName, String language, String rootNamespace, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name, Boolean force, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Object reference not set to an instance of an object.
I don't know if this is relevant or not, but in my web.config, there is a Default Connection that is already pre-set when i first created my project. When i first did Enable-Migrations i had to specify which connection it was. I've removed that line but it still doesn't work.

Previously when i did the add-migration, it didn't work because i simply created a class and added declaration of the respective strings, integer, etc. as variables like this:
Public Property id As String
Now it suddenly popped into my mind that i had to give a more elaborate description on each of the variables such as below:
<Key>
<StringLength(20)>
Public Property id As String
Now it works =')

Related

How to create new migration on vs code in N-Tier project

I want to create migration on my N-Tier project on VS Code, but when I select my Data project and run the command, I get the error below. Can you help me?
System.MissingMethodException: No parameterless constructor defined for this object.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContextFromFactory(Type factory)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
No parameterless constructor defined for this object.
Possibly you have defined parametric constructor(s) for one (or more) of your model classes and hence prevented the compiler to automatically generate a default (parameter-less) constructor for your model class(es) and since entity framework needs a default constructor for every model class, it's throwing an exception.
What you need to do is to define a parameter-less constructor for every model that has a user-defined parametric constructor.

Simple Injector instance is requested outside the context of an active (async scope) scope

I'm trying to inject my IAuthorizationRepository into my VB Web App using SimpleInjector.
Public Class IdentityPackage
Implements IPackage
Public Sub RegisterServices(container As Container) Implements IPackage.RegisterServices
container.Register(Of IUserStore(Of User, Integer), UserStore)(Lifestyle.Scoped)
container.Register(Of IAuthorizationRepository, AuthorizationRepository)(Lifestyle.Scoped)
container.Register(Of ISession, Session)()
End Sub
End Class
Here's my startup.
Public Partial Class Startup
Public Sub Configuration(app As IAppBuilder)
Dim container = ConfigureSimpleInjector(app)
Dim config = New HttpConfiguration() With {
.DependencyResolver = New SimpleInjectorWebApiDependencyResolver(container)
}
ConfigureOAuth(app, container)
WebApiConfig.Register(config)
app.UseCors(CorsOptions.AllowAll)
app.UseWebApi(config)
End Sub
End Class
And here's my ConfigureOAuth.
Public Sub ConfigureOAuth(app As IAppBuilder, container As Container)
Dim authRepositoryFactory As Func(Of IAuthorizationRepository) = container.GetInstance(Of IAuthorizationRepository)
Dim authorizationOptions = New OAuthAuthorizationServerOptions() With {
.AllowInsecureHttp = True,
.TokenEndpointPath = New PathString("/api/token"),
.AccessTokenExpireTimeSpan = TimeSpan.FromHours(4),
.Provider = New AuthorizationServerProvider(authRepositoryFactory)
}
' Token Generation
app.UseOAuthAuthorizationServer(authorizationOptions)
app.UseOAuthBearerAuthentication(New OAuthBearerAuthenticationOptions())
End Sub
When it gets to the first line under ConfigureOAuth, it throws the error The AuthorizationRepository is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.
The strange thing is that I'm converting an existing, and fully functional C# project into VB, and this is the VB equivalent of the codebase in C#, but the C# code does not have this problem. This makes me feel like the issue lies in how VB handles the code, as opposed to C#, but I don't see how that could be the case with this example. Can anyone tell me what's going wrong?
The following is my stack trace:
[ActivationException: The AuthorizationRepository is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.]
SimpleInjector.Scope.GetScopelessInstance(ScopedRegistration`1 registration) +168
SimpleInjector.Scope.GetInstance(ScopedRegistration`1 registration, Scope scope) +52
SimpleInjector.Advanced.Internal.LazyScopedRegistration`1.GetInstance(Scope scope) +158
lambda_method(Closure ) +223
SimpleInjector.InstanceProducer.BuildAndReplaceInstanceCreatorAndCreateFirstInstance() +32
SimpleInjector.InstanceProducer.GetInstance() +235
SimpleInjector.Container.GetInstanceForRootType() +154
SimpleInjector.Container.GetInstance() +146
ClientWebAppVB.Api.Startup.ConfigureOAuth(IAppBuilder app, Container container) in C:\Projects\TEST\ClientWebAppVB\ClientWebAppVB.Api\App_Start\OAuthConfig.vb:10
ClientWebAppVB.Api.Startup.Configuration(IAppBuilder app) in C:\Projects\TEST\ClientWebAppVB\ClientWebAppVB.Api\Startup.vb:15
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +160
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
Owin.Loader.<>c__DisplayClass12.<MakeDelegate>b__b(IAppBuilder builder) +66
Owin.Loader.<>c__DisplayClass1.<LoadImplementation>b__0(IAppBuilder builder) +123
Microsoft.Owin.Host.SystemWeb.<>c__DisplayClass2.<InitializeBlueprint>b__0(IAppBuilder builder) +71
Microsoft.Owin.Host.SystemWeb.OwinAppContext.Initialize(Action`1 startup) +462
Microsoft.Owin.Host.SystemWeb.OwinBuilder.Build(Action`1 startup) +40
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +70
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +106
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +536
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +173
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296
[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +10044576
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +95
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
The strange thing is that I'm converting an existing, and fully functional C# project into VB, and this is the VB equivalent of the codebase in C#, but the C# code does not have this problem
Well this is actually not the equivalent of the c# version. And unless you changed Option Explicit and Option Strict settings I'm pretty sure the code you show does not even compile. Or in your real code you omitted the As Func(Of IAuthorizationRepository) clause.
In c# this two lines are 2 totally different things:
// create a delegate
Func<IAuthorizationRepository> authRepositoryFactory =
container.GetInstance<IAuthorizationRepository>;
// and directly call a delegate or method
Func<IAuthorizationRepository> authRepositoryFactory =
container.GetInstance<IAuthorizationRepository>();
And here the second line does not compile. This line returns IAuthorizationRepository and therefore is not assignable to Func<IAuthorizationRepository>.
In Vb.Net however the following lines are exactly the same. The braces of a method call are totally optional.
' Directly call the method
Dim authRepositoryFactory = container.GetInstance(Of IAuthorizationRepository)
' And directy call the method
Dim authRepositoryFactory = container.GetInstance(Of IAuthorizationRepository)()
If you hover over authRepositoryFactory you'll see that the inferred type is IAuthorizationRepository for both lines.
To create a delegate instead of directly invoking it in VB you need to use the AddressOf Operator
Dim authRepositoryFactory = New Func(Of IAuthorizationRepository)(
AddressOf container.GetInstance(Of IAuthorizationRepository))
'or
Dim authRepositoryFactory As Func(Of IAuthorizationRepository) =
AddressOf container.GetInstance(Of IAuthorizationRepository)
If you would hover over authRepositoryFactory you'll see this is actually a Func (Of IAuthorizationRepository)

TravelItineraryReadService VB error

When trying to use the TravelItineraryReadService 3.8.0 service via VB i get the following error just by doing
Private service As TravelItineraryReadService
service = New TravelItineraryReadService
the error output:
at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)
at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)
at System.Xml.Serialization.XmlSerializer.GetSerializersFromCache(XmlMapping[] mappings, Type type)
at System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[] mappings, Type type)
at System.Web.Services.Protocols.SoapClientType..ctor(Type type)
at System.Web.Services.Protocols.SoapHttpClientProtocol..ctor()
at PricingContingency.TravelItineraryRQ1.TravelItineraryReadService..ctor()
i am using visual studio 2015,
added the WSDL as
it doesn't matter if i add the header info or not. it always fails.
This is due to response object issue in generated web service proxy class.
Changed the following and works well for me.
1.
Private associatedDataField()() As TravelItineraryReadRSTravelItineraryItineraryInfoItineraryPricingPriceQuoteMiscInformationTicketingFeesFeeInformationAssociatedDataAssociatedDataItem
----change as below-- Private associatedDataField() As
TravelItineraryReadRSTravelItineraryItineraryInfoItineraryPricingPriceQuoteMiscInformationTicketingFeesFeeInformationAssociatedDataAssociatedDataItem
Public Property AssociatedData() As TravelItineraryReadRSTravelItineraryItineraryInfoItineraryPricingPriceQuoteMiscInformationTicketingFeesFeeInformationAssociatedDataAssociatedDataItem()()
----change as below--
Public Property AssociatedData() As TravelItineraryReadRSTravelItineraryItineraryInfoItineraryPricingPriceQuoteMiscInformationTicketingFeesFeeInformationAssociatedDataAssociatedDataItem()

WCF Read data issue from service

I am tying to get the generic List of user List<User> object from my web service to my web application. probably this is common issue. i searched a lot but got different remedies with each link. so finally i decide to ask to chaps over here... anyways
I am using console application for fetching the data from my hosted wcf web service. where as my WCf web service having the Entity framework 4.1. am using objects from its model class. when i tried to add service reference to my web application , it typically generates the proxy in web app. i am able to post data means i could create user. but while getusers which is returning List , getting following exceptions...:
Exception:
An error occurred while receiving the HTTP response to
http://myserver/AdminService/MyAdminService.svc. This could be due to
the service endpoint binding not using the HTTP protocol. This could
also be due to an HTTP request context being aborted by the server
(possibly due to the service shutting down). See server logs for more
details.
Inner Exception is :
The underlying connection was closed: An unexpected error occurred
on a receive
and inner-inner exception is : Unable to read data from the
transport connection: An existing connection was forcibly closed by
the remote host.
with message : An existing connection was forcibly closed by the
remote host
Error Code :10054
Where as Event log saying :
A message was not logged.
Exception: System.ServiceModel.CommunicationException: There was
an error while trying to serialize parameter
http://tempuri.org/:getUsersResult. The InnerException message was
'Type
'System.Data.Entity.DynamicProxies.User_00DEC686D7E21DB0D84B595F647A03FFB4943938F76E8C3DBBE0F77F8BC29A1D'
with data contract name
'User_00DEC686D7E21DB0D84B595F647A03FFB4943938F76E8C3DBBE0F77F8BC29A1D:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies'
is not expected. Consider using a DataContractResolver or add any
types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer.'. Please see
InnerException for more details. --->
System.Runtime.Serialization.SerializationException: Type
'System.Data.Entity.DynamicProxies.User_00DEC686D7E21DB0D84B595F647A03FFB4943938F76E8C3DBBE0F77F8BC29A1D'
with data contract name
'User_00DEC686D7E21DB0D84B595F647A03FFB4943938F76E8C3DBBE0F77F8BC29A1D:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies'
is not expected. Consider using a DataContractResolver or add any
types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer.
at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract
dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean
verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type
declaredType)
at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator
xmlWriter, Object obj, RuntimeTypeHandle objectTypeHandle, Type
objectType, Int32 declaredTypeID, RuntimeTypeHandle
declaredTypeHandle, Type declaredType)
at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator
xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType,
Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator
xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType,
Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
at WriteArrayOfUserToXml(XmlWriterDelegator , Object ,
XmlObjectSerializerWriteContext , CollectionDataContract )
at
System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator
xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
at
System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator
writer, Object graph, DataContractResolver dataContractResolver)
at
System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator
writer, Object graph, DataContractResolver dataContractResolver)
at
System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator
writer, Object graph, DataContractResolver dataContractResolver)
at
System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionaryWriter
writer, Object graph)
at
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter
writer, PartInfo part, Object graph)
--- End of inner exception stack trace ---
at
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter
writer, PartInfo part, Object graph)
at
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameter(XmlDictionaryWriter
writer, PartInfo part, Object graph)
at
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter
writer, MessageVersion version, String action, MessageDescription
messageDescription, Object returnValue, Object[] parameters, Boolean
isRequest)
at
System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter
writer)
at
System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWriter
writer)
at
System.ServiceModel.Channels.Message.ToString(XmlDictionaryWriter
writer)
at
System.ServiceModel.Diagnostics.MessageLogTraceRecord.WriteTo(XmlWriter
writer)
at
System.ServiceModel.Diagnostics.MessageLogger.LogInternal(MessageLogTraceRecord
record)
at
System.ServiceModel.Diagnostics.MessageLogger.LogMessageImpl(Message&
message, XmlReader reader, MessageLoggingSource source)
at
System.ServiceModel.Diagnostics.MessageLogger.LogMessage(Message&
message, XmlReader reader, MessageLoggingSource source)
Process Name: w3wp
Process ID: 5928
What should be this issue. me and team searching for this since 3 days. but unfortunately not overcome so far...
I tried lot of stuffs like add serializable attribute, endpoint modifications ... i can not recollect all :) ... probably you may give us right directions...
The reason is that EF classes are by default proxied at runtime to support lazy loading and dynamic change tracking. So you don't serialize User class but class derived from User at runtime. WCF doesn't like that. Turn off proxy creation on your context.
context.Configuration.ProxyCreationEnabled = false;

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.