nhibernate / fluent-nhibernate

Fluent NHibernate!
BSD 3-Clause "New" or "Revised" License
1.66k stars 687 forks source link

A non collectible assembly may not reference a collectible assembly #512

Open MikeTraceur opened 2 years ago

MikeTraceur commented 2 years ago

Hello,

I am still failing to configure fluent nhibernate in my project. switching from java with spring and hibernate, nhibernate was my first choise and without the need to define mapping xmls it is now fluent nhibernate. But I always get this error

ystem.TypeInitializationException: The type initializer for 'Altv_Roleplay.Database.Config.NHibernateHelper' threw an exception.
 ---> FluentNHibernate.Cfg.FluentConfigurationException: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.

 ---> FluentNHibernate.Cfg.FluentConfigurationException: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.

 ---> NHibernate.MappingException: Could not compile the mapping document: (XmlDocument)
 ---> System.TypeInitializationException: The type initializer for 'NHibernate.Cfg.NamedXmlDocument' threw an exception.
 ---> System.NotSupportedException: A non-collectible assembly may not reference a collectible assembly.
   at System.Reflection.Emit.ModuleBuilder.GetTypeRef(QCallModule module, String strFullName, QCallModule refedModule, String strRefedModuleFileName, Int32 tkResolution)
   at System.Reflection.Emit.ModuleBuilder.GetTypeRefNested(Type type, Module refedModule, String strRefedModuleFileName)
   at System.Reflection.Emit.ModuleBuilder.GetTypeTokenWorkerNoLock(Type type, Boolean getGenericDefinition)
   at System.Reflection.Emit.ModuleBuilder.GetTypeTokenInternal(Type type, Boolean getGenericDefinition)
   at System.Reflection.Emit.ILGenerator.Emit(OpCode opcode, Type cls)
   at System.Xml.Serialization.CodeGenerator.Castclass(Type target)
   at System.Xml.Serialization.CodeGenerator.InternalConvert(Type source, Type target, Boolean isAddress)
   at System.Xml.Serialization.SourceInfo.InternalLoad(Type elementType, Boolean asAddress)
   at System.Xml.Serialization.XmlSerializationWriterILGen.WriteElement(SourceInfo source, ElementAccessor element, String arrayName, Boolean writeAccessor)
   at System.Xml.Serialization.XmlSerializationWriterILGen.WriteElements(SourceInfo source, String enumSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, String arrayName, Boolean writeAccessors, Boolean isNullable)
   at System.Xml.Serialization.XmlSerializationWriterILGen.WriteMember(SourceInfo source, String choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc memberTypeDesc, Boolean writeAccessors)
   at System.Xml.Serialization.XmlSerializationWriterILGen.GenerateTypeElement(XmlTypeMapping xmlTypeMapping)
   at System.Xml.Serialization.XmlSerializationWriterILGen.GenerateElement(XmlMapping xmlMapping)
   at System.Xml.Serialization.TempAssembly.GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace)
   at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location)
   at System.Xml.Serialization.XmlSerializer.GenerateTempAssembly(XmlMapping xmlMapping, Type type, String defaultNamespace, String location)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type)
   at NHibernate.Cfg.NamedXmlDocument..cctor()
   --- End of inner exception stack trace ---
   at NHibernate.Cfg.NamedXmlDocument..ctor(String name, XmlDocument document)
   at NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
   --- End of inner exception stack trace ---
   at NHibernate.Cfg.Configuration.LogAndThrow(Exception exception)
   at NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
   at NHibernate.Cfg.Configuration.AddXmlReader(XmlReader hbmReader, String name)
   at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
   at NHibernate.Cfg.Configuration.AddDocument(XmlDocument doc, String name)
   at NHibernate.Cfg.Configuration.AddDocument(XmlDocument doc)
   at FluentNHibernate.PersistenceModel.Configure(Configuration cfg)
   at FluentNHibernate.Cfg.MappingConfiguration.Apply(Configuration cfg)
   at FluentNHibernate.Cfg.FluentConfiguration.BuildConfiguration()
   --- End of inner exception stack trace ---
   at FluentNHibernate.Cfg.FluentConfiguration.BuildConfiguration()
   at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory()

   --- End of inner exception stack trace ---
   at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory()
   at Altv_Roleplay.Database.Config.NHibernateHelper.FluentConfigure() in E:\dev\ls-reallife-altv\MAPPE\Altv-Roleplay\Database\Config\NHibernateHelper.cs:line 40
   at Altv_Roleplay.Database.Config.NHibernateHelper..cctor() in E:\dev\ls-reallife-altv\MAPPE\Altv-Roleplay\Database\Config\NHibernateHelper.cs:line 23

   --- End of inner exception stack trace ---
   at Altv_Roleplay.Database.Config.NHibernateHelper.GetCurrentSession() in E:\dev\ls-reallife-altv\MAPPE\Altv-Roleplay\Database\Config\NHibernateHelper.cs:line 26
   at Altv_Roleplay.Database.DatabaseHandler.LoadAllPlayerCharacters() in E:\dev\ls-reallife-altv\MAPPE\Altv-Roleplay\Database\DatabaseHandler.cs:line 86
   at Altv_Roleplay.Main.OnStart() in E:\dev\ls-reallife-altv\MAPPE\Altv-Roleplay\Main.cs:line 48
   at AltV.Net.ModuleWrapper.OnStartResource(IntPtr serverPointer, IntPtr resourcePointer, String resourceName, String entryPoint)

My Configuration looks like:

namespace Altv_Roleplay.Database.Config
{
    static class NHibernateHelper
    {
        private const string CurrentSessionKey = "nhibernate.current_session";
        private static readonly ISessionFactory _sessionFactory;
        static NHibernateHelper()
        {
            _sessionFactory = FluentConfigure();
        }
        public static ISession GetCurrentSession()
        {
            return FluentConfigure().OpenSession();
        }
        public static void CloseSession()
        {
            _sessionFactory.Close();
        }
        public static void CloseSessionFactory()
        {
            _sessionFactory?.Close();
        }

        public static ISessionFactory FluentConfigure()
        {
            ISessionFactory sessionFactory = Fluently.Configure()
                .Database(
                    MySQLConfiguration.Standard.ConnectionString(c =>
                        c.Is("Server=IP;Port=3306;Database=DATABASE;Uid=USER;Pwd=PASSWORD")
                    )
                )
                .Cache(
                    c => c.UseQueryCache()
                        .UseSecondLevelCache()
                        .ProviderClass<NHibernate.Cache.HashtableCacheProvider>())
                .Mappings(m =>
                {
                    m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly());
                })
                .BuildSessionFactory();

            return FluentConfiguration().BuildSessionFactory();
        }
    }
}

My Mapping:

namespace Altv_Roleplay.Database.Mappings
{
    public partial class AccountCharactersMapping : ClassMap<Accounts_Characters>
    {
        public AccountCharactersMapping()
        {
            Id(x => x.charId).GeneratedBy.Native();
            Map(x => x.charname);
            ...
        }
    }
}

My Entity:

namespace Altv_Roleplay.models
{
    public class Accounts_Characters
    {
        public virtual int charId { get; set; }
        public virtual string charname { get; set; }
        ....
    }
}        

I get this error when I try to open the session at:

    internal static void LoadAllPlayerCharacters()
        {
            ISession session = NHibernateHelper.GetCurrentSession(); // Here is when the Error appears
            using (ITransaction tx = session.BeginTransaction())
            {
               ...
            }

I also tried to add a hibernate xml config:

<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
  <session-factory name="NHibernate.Test">
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="dialect">NHibernate.Dialect.MySQL55InnoDBDialect</property>
    <property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
    <property name="connection.connection_string">server=SERVER;database=DATABASE;uid=USER;pwd=PASSWORD</property>
    <property name="show_sql">true</property>
  </session-factory>
</hibernate-configuration> 

But still no success. I tried it with netcoreapp3.1, net5.0 but now I am forced to switch to net6.0 due to other dependencies

hazzik commented 2 years ago

@MikeTraceur what project type is this? Is it Xamarin?

Try running sgen on NHibernate.dll and include NHibernate.XmlSerializers.dll to your project.