NHibernate unable to create SessionFactory - c#

I'm having a bit of trouble setting up NHibernate, and I'm not too sure what the problem is exactly. I'm attempting to save a domain object to the database (Oracle 10g XE). However, I'm getting a TypeInitializationException while trying to create the ISessionFactory. Here is what my hibernate.cfg.xml looks like:
<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="MyProject.DataAccess">
<property name="connection.driver_class">NHibernate.Driver.OracleClientDriver</property>
<property name="connection.connection_string">
User ID=myid;Password=mypassword;Data Source=localhost
</property>
<property name="show_sql">true</property>
<property name="dialect">NHibernate.Dialect.OracleDialect</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<mapping resource="MyProject/Domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I created a DAO which I will use to persist domain objects to the database. The DAO uses a HibernateUtil class that creates the SessionFactory. Both classes are in the DataAccess namespace along with the Hibernate configuration. This is where the exception is occuring. Here's that class:
public class HibernateUtil
{
private static ISessionFactory SessionFactory = BuildSessionFactory();
private static ISessionFactory BuildSessionFactory()
{
try
{
// This seems to be where the problem occurs
return new Configuration().Configure().BuildSessionFactory();
}
catch (TypeInitializationException ex)
{
Console.WriteLine("Initial SessionFactory creation failed." + ex);
throw new Exception("Unable to create SessionFactory.");
}
}
public static ISessionFactory GetSessionFactory()
{
return SessionFactory;
}
}
The DataAccess namespace references the NHibernate DLLs. This is virtually the same setup I've used with Hibernate in Java, so I'm not entirely sure what I'm doing wrong here. Any ideas?
Edit
The innermost exception is the following:
"Could not find file 'C:\Users\Tyler\Documents\Visual Studio 2010\Projects\MyProject\MyProject\ConsoleApplication\bin\Debug\hibernate.cfg.xml'."
ConsoleApplication contains the entry point where I've created a User object and am trying to persist it with my DAO. Why is it looking for the configuration file there? The actual persisting takes place in the DAO, which is in DataAccess. Also, when I add the configuration file to ConsoleApplication, it still does not find it.

It is looking for the configuration file in that directory because that is the default location for NHibernate to look for a configuration file. Note that this is a directory, it has nothing to do with namespaces. You need to set the properties on the hibernate.cfg.xml file in your project to copy to output directory.

I think this issue will be resolved if you can copy the cfg.xml file to the folder that contain the NHibernate assembly

Related

NHibernate mapping error ([EntityName] not mapped)

My project (c#, nhibernate, npgsql, nlog) has one entity named Entry and should be mapped to the database table named test. Table contains some test entries.
My application code is as follows:
public void work()
{
ISessionFactory sessions = new Configuration().Configure().BuildSessionFactory();
ISession session = sessions.OpenSession();
IList<Entry> entries = session.CreateQuery("from Entry").List<Entry>();
foreach (Entry e in entries)
{
logger.Debug("Entry: " + e.id + " with " + e.name);
}
}
The Entry entity looks like this:
namespace pgsql
{
class Entry
{
public virtual int id { get; set; }
public virtual string name { get; set; }
}
}
My NHibernate configuration is structured as below:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.driver_class">NHibernate.Driver.NpgsqlDriver</property>
<property name="dialect">NHibernate.Dialect.PostgreSQLDialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="default_catalog">test</property>
<property name="default_schema">test</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<property name="connection.connection_string">server=localhost;database=*****;uid=*****;pwd=*****;</property>
</session-factory>
</hibernate-configuration>
The Entry entity configuration is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping schema="test" xmlns="urn:nhibernate-mapping-2.2">
<class name="Entry" table="test">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>
This throws below error:
Entry is not mapped [from Entry]
I have made sure, that Visual Studio is copying all hbm.xml files to the output directory. What am i missing?
Edit in response to your answer:
the solution was to initialize with the Assembly:
ISessionFactory sessions = new Configuration().Configure().AddAssembly(Assembly.GetExecutingAssembly()).BuildSessionFactory();
but i still don't know, why it has to be like that.
I will explain why it has to be like that.
Your entity is defined in same assembly as that of your application.
When you call Configuration().Configure().BuildSessionFactory(), actually all your HBM files are being ignored. You need to do either of following to add HBM file to Configuration instance:
Use new Configuration().AddFile("MyFile.hbm.xml") for each individual HBM file.
Use new Configuration().Configure().AddAssembly(YourAssembly()) to tell NHibernate to look for all HBM files and add all those for you.
Other ways mentioned in document linked below.
As you was not doing either of this, there were no entity configurations added to Configuration. Whey you try to run your HQL query, NHibernate was looking for Entry entity which was not defined (added to Configuration). Hence was the error.
As you mentioned in your answer, you choose second way to add HBM files to Configuration and issue went away.
Another alternative (probably the best) way is to let NHibernate load all of the mapping files contained in an Assembly:
Configuration cfg = new Configuration()
.AddAssembly( "NHibernate.Auction" );
Then NHibernate will look through the assembly for any resources that end with .hbm.xml. This approach eliminates any hardcoded filenames and ensures the mapping files in the assembly get added.
Please refer doc for more details.
Original Answer
Entity name should include namespace as well.
IList<Entry> entries = session.CreateQuery("from pgsql.Entry").List<Entry>();
To make refactoring bit easy, you may also change to something like following:
var queryString = string.Format("from {0}", typeof(Entry));
IList<Entry> entries = session.CreateQuery(queryString).List<Entry>();
Please refer section 14.2. The from clause from docs.
Not a part of your problem but, call to BuildSessionFactory is costly. You do not need to repeat it. You can call it at the startup of your application may be and maintain the instance of ISessionFactory for future use.
the solution was to initialize with the Assembly:
ISessionFactory sessions = new Configuration().Configure().AddAssembly(Assembly.GetExecutingAssembly()).BuildSessionFactory();
but i still don't know, why it has to be like that.

OracleDataClientBatchingBatcherFactory Throws Null Reference Exception

We're using NHibernate version 4.0.4.4000 and configuring it with FluentNHibernate version 2.0.3.0.
I'm trying to setup batching on an Oracle connection with the Oracle Data Client Batching Batcher Factory (OracleDataClientBatchingBatcherFactory) and using the following code to create NHConfiguration:
var cfg = new NHibernate.Cfg.Configuration().DataBaseIntegration(prop => {
prop.BatchSize = 1000;
prop.Batcher<OracleDataClientBatchingBatcherFactory>();
});
Getting the following exception on session flush:
System.NullReferenceException: Object reference not set to an instance of an object.
at NHibernate.AdoNet.OracleDataClientBatchingBatcher.SetArrayBindCount(Int32 arraySize)
at NHibernate.AdoNet.OracleDataClientBatchingBatcher.DoExecuteBatch(IDbCommand ps) ...
It looks like SetArrayBindCount method is using reflection to set ArrayBindCount property in OracleCommand. This method throws a null reference exception.
Did anyone else experience the same problem? Am I missing something or it's a bug in OracleDataClientBatchingBatcher?
I do not get this problem when I use the SQL Client Batching Batcher Factory (SqlClientBatchingBatcherFactory)
var cfg = new NHibernate.Cfg.Configuration().DataBaseIntegration(prop => {
prop.BatchSize = 1000;
prop.Batcher<SqlClientBatchingBatcherFactory>();
});
Any help will be greatly appreciated as this is currently blocking us.
Question Origin: https://groups.google.com/forum/#%21topic/nhusers/-rzStjZSxmI
Spending a hours I found that the root cause of the problem is that OracleDataClientBatchingBatcher isn't compatible with all Oracle connection drivers, supported by nHibernate. In my case it was NHibernate.Driver.OracleClientDriver which is in fact a wrapper of System.Data.OracleClient.Connection and System.Data.OracleClient.OracleCommand.
public OracleClientDriver() :
base(
"System.Data.OracleClient",
"System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"System.Data.OracleClient.OracleConnection",
"System.Data.OracleClient.OracleCommand") { }
If you inspect OracleCommand class you'll see that it doesn't really contain the property 'ArrayBindCount'. In addition to this MSDN tells that classes from System.Data.OracleClient namespace are deprecated:
This types in System.Data.OracleClient are deprecated and will be removed in a future version of the .NET Framework. For more information, see Oracle and ADO.NET.
To solve the problem you have to choose a NHibernate.Driver.OracleManagedDataClientDriver as connection driver which is using Oracle ADO.NET. Here is a part of nHibernate config file that does this:
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider
</property>
<property name="connection.driver_class">
NHibernate.Driver.OracleManagedDataClientDriver
</property>
<property name="dialect">
NHibernate.Dialect.Oracle10gDialect
</property>
Also, you'll need to install Oracle.ManagedDataAccess package from NuGet
PM> Install-Package Oracle.ManagedDataAccess
This approach is working perfectly for me

The mapping of CLR type to EDM type is ambiguous with EF 6 & 5?

Please any one can help me to fix this error?
Schema specified is not valid. Errors:
The mapping of CLR type to EDM type is ambiguous because multiple CLR types match the EDM type 'City_DAL'. Previously found CLR type 'CeossDAL.City_DAL', newly found CLR type 'CeossBLL.City_DAL'.
The main problem that I have DAL and this contains the EF and BLL and this contains the same classes of the DAL but differ in the namespace and this is what cause the problem
I can't know how to get rid of these problem, can you please help me?
Also I will be appreciated if some one give me sample to use n-tier architecture with EF
Thank you
Don't use classes with the same unqualified name - EF uses only class names to identify the type mapped in EDMX (namespaces are ignored) - it is a convention to allow mapping classes from different namespaces to single model. The solution for your problem is to name your classes in BLL differently.
Workaround: Change a property on one of the two identical classes.
EF matches on class name AND class properties. So I just changed a property name on one of the EF objects, and the error is gone.
As #Entrodus commented on one of the other answers:
EF collision happens only when two classes have the same name AND the
same set of parameters.
This MSDN forum question might be helpful. It suggest placing the BLL and DAL classes in separate assemblies.
In some cases this is more of a symptom than the actual problem. For me, it usually pops up when I try to call a function inside a Linq query without calling .ToList() first.
E.g. the error that brought me here was caused because I did this:
var vehicles = DB.Vehicles.Select(x => new QuickSearchResult()
{
BodyText = x.Make + " " + x.Model + "<br/>"
+ "VIN: " + x.VIN + "<br/>"
+ "Reg: " + x.RegistrationNumber +"<br/>"
+ x.AdditionalInfo
type = QuickSearchResultType.Vehicle,//HERE. Can't use an enum in an IQueryable.
UniqueId = x.VehicleID
});
I had to call .ToList(), then iterate through each item and assign the type to it.
For EF 6.x, I found some notes at https://github.com/aspnet/EntityFramework/issues/941 and fixed this in my solution by adding annotation to the EDM type.
I edited the EDMX file manually and changed a line like this:
<EntityType Name="CartItem">
to this:
<EntityType Name="CartItem" customannotation:ClrType="EntityModel.CartItem">
or use this if you have existing type elsewhere:
<EntityType Name="CartItem" customannotation:ClrType="MyApp.CartItem, MyApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
where EntityModel is the namespace used for my EF model, and MyApp is the namespace of a business object
I got the error above because for both connection strings, I had the same value for metadata specified in my main project's config file, like below:
<add name="EntitiesA" connectionString="metadata=res://*/EntitiesA.csdl|res://*/EntitiesA.ssdl|res://*/EntitiesA.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=MyDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="EntitiesB" connectionString="metadata=res://*/EntitiesA.csdl|res://*/EntitiesA.ssdl|res://*/EntitiesA.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=MyDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I ended up copying the correct connection string from the EntitiesB's project's config file.
This may not have been available when the question was asked, but another solution is to delete the EDMX and recreate it as a code-first entity data model. In EF6, with code-first, you can map two classes with the same name from different model namespaces without creating a conflict.
To create the entity data model in Visual Studio (2013), go to "Add" > "New Item..." > "ADO.NET Entity Data Model". Be sure to choose the "Code First from database" option.
Another reason you might get this error:
If you're loading custom assemblies with Assembly.LoadFile that have edmx files, that have already been loaded into memory. This creates duplicate classes that entity framework doesn't like.
For me this was because I was attempting to access a type with the same name on the wrong context instance.
Say both ContextA and ContextB have SomeType. I was trying to access ContextA.SomeType on an instance of ContextB.
Just add the EntityFramework as "Code First from database" and not as "EF Designer from database". This resolved my problem, but it has a dark side, if you change your database you have to remove all the classes and add it again, or just edit the classes, I use the last when I change properties of the columns, like "Allows null" or the size of a string. But if you add columns I recomend remove and add again the classes.
I was able to solve this issue without renaming the classes, properties, or metadata.
I had my project setup with a T4 transform creating entity objects in a DAL project, and a T4 transform creating domain objects in a Domain project, both referencing the EDMX to generate identical objects, and then I was mapping the DAL objects to the Domain objects.
The error only occurred when I was referencing other classes (enums in my case) from the Domain assembly in my queries. When I removed them, the error went away. It looks like EF was loading up my Domain assembly because of this, seeing the other identically named classes, and blowing up.
To resolve this, I made a separate assembly that only contained my T4 transformed Domain classes. Since I never need to use these inside a query (only after the query to map to), I no longer have this issue. This seems cleaner and easier than the answers below.
if you have 2 connection string in web config but you want to use one connection string
You use dynamic create connection string other entities.
I have edmx(db first) and code first Entities in my solution.
I use this class in Code first entities.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity.Core.EntityClient;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Data
{
public class SingleConnection
{
private SingleConnection() { }
private static SingleConnection _ConsString = null;
private String _String = null;
public static string ConString
{
get
{
if (_ConsString == null)
{
_ConsString = new SingleConnection { _String = SingleConnection.Connect() };
return _ConsString._String;
}
else
return _ConsString._String;
}
}
public static string Connect()
{
string conString = ConfigurationManager.ConnectionStrings["YourConnectionStringsName"].ConnectionString;
if (conString.ToLower().StartsWith("metadata="))
{
System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder efBuilder = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(conString);
conString = efBuilder.ProviderConnectionString;
}
SqlConnectionStringBuilder cns = new SqlConnectionStringBuilder(conString);
string dataSource = cns.DataSource;
SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()
{
DataSource = cns.DataSource, // Server name
InitialCatalog = cns.InitialCatalog, //Database
UserID = cns.UserID, //Username
Password = cns.Password, //Password,
MultipleActiveResultSets = true,
ApplicationName = "EntityFramework",
};
//Build an Entity Framework connection string
EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()
{
Provider = "System.Data.SqlClient",
Metadata = "res://*",
ProviderConnectionString = sqlString.ToString()
};
return entityString.ConnectionString;
}
}
}
And when I call entities
private static DBEntities context
{
get
{
if (_context == null)
_context = new DBEntities(SingleConnection.ConString);
return _context;
}
set { _context = value; }
}
I Think u Have a Class X named "MyClass" in Entity Models and Another Class Called "MyClass" in the same WorkFolder or Extended of the first Class.
That is my problem and i fix it.
I found that using the custom annotation solution works with EF 6.2.0. Just make sure to change in the ConceptualModels node and use full namespace for the type.
<edmx:ConceptualModels>
<Schema Namespace="Sample.Access.Data.Ef" Alias="Self" annotation:UseStrongSpatialTypes="false" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns:customannotation="http://schemas.microsoft.com/ado/2013/11/edm/customannotation" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
<EntityType Name="DbTableName" customannotation:ClrType="Sample.Access.Data.Ef.DbTableName, Sample.Access.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<Key>
<PropertyRef Name="DbTableNameId" />
</Key>
<Property Name="DbTableNameId" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="OptionName" Type="String" MaxLength="100" FixedLength="false" Unicode="false" Nullable="false" />
<Property Name="Value" Type="String" MaxLength="500" FixedLength="false" Unicode="false" Nullable="false" />
<Property Name="UpdatedDate" Type="DateTime" Nullable="false" Precision="3" />
</EntityType>
<EntityContainer Name="MyEntities" annotation:LazyLoadingEnabled="true" customannotation:UseClrTypes="true">
<EntitySet Name="DbTableNames" EntityType="Self.DbTableName" />
</EntityContainer>
</Schema>
</edmx:ConceptualModels>
There is a library called AutoMapper which you can download. It helps you to define class mappings from one type to another.
Mapper.CreateMap<Model.FileHistoryEFModel, DataTypes.FileHistory>();
Mapper.CreateMap<DataTypes.FileHistory, Model.FileHistoryEFModel>();

Fluent NHibernate - exception occurred during configuration of persistence layer

I am using Fluent NHibernate with an external 'hibernate.cfg.xml' file.
Following is the configuration code where I am getting error:
var configuration = new Configuration();
configuration.Configure();
_sessionFactory = Fluently.Configure(configuration)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Template>())
.BuildSessionFactory();
return _sessionFactory;
But When NHibernate is trying to configure, I am getting floowing error:
An exception occurred during configuration of persistence layer.
The inner exception says:
The ProxyFactoryFactory was not configured.
Initialize 'proxyfactory.factory_class' property of the session-factory configuration section with one of the available NHibernate.ByteCode providers.
I googled and according to some solutions I found, I have made following changes:
Add following dlls to my app bin:
Castle.Core.dll, Castle.DynamicProxy2.dll, NHibernate.ByteCode.Castle.dll
Added follwing property in hibernate.cfg.xml
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
But still I am getting the same exception.
I had this error too. It fires when you don't copy the mapping file (hibernate.cfg.xml) to the build directory.
Solution:
In Solution explorer, right click on the mapping file (hibernate.cfg.xml), choose Properties, then make sure that Copy To Output Directory has Copy if newer selected).
As Alex InTechno said, this might be the error in the definition of your Mapping files or in mapped entities. I experienced the same error, when I have forgot that all properties in mapped classes have to be defined as virtual.
public String Name {get;set;}
public virtual String Name { get; set; }
The problem might be in your hibernate.cfg.xml, double check that is using 2.2 version and if well formed.
The mapping should start like this:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
Along with the error you post, maybe more information is supplied because that error is quite generic to the configuration parser. If not, maybe you can give more details of your hibernate.cfg.xml.
Exception with the text of PotentialReasons
* Database was not configured through Database method.
might be also thrown by the FluentConfiguration.BuildConfiguration() method in the case your mappings are wrong (i.e. .*Map classes were not successfully parsed) and you have configured database not with .Database() method.
This is a bit confusingly that it is discovered only at the step of building configuration, not when these classes are being added from assembly (by AddFromAssemblyOf<>)
You can check whether your *Map classes are successfully converted to HBM by executing a line
m.FluentMappings.Add(typeof(YourMappedTypeMap)).ExportTo(#"c:\Temp\fluentmaps"))
I had the same issue with NUnit tests under Resharper 8.1
Tick "ReSharper | Options | Tools | Unit Testing | Use separate AppDomain for each assembly with tests" checkbox fixed it
Well, I was able to resolve that error by placing .cfg.xml file in bin of calling app.
But now, I am getting another error :-(
FluentNHibernate.Cfg.FluentConfigurationException was unhandled
Message: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
* Database was not configured through Database method.
Here is my hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Server=dev\sql2005;Initial Catalog=TestDB;Integrated Security=True</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
Any thoughts?
Trying to configure the database in App.config and the mappings via Fluent NHibernate, I also got a FluentNHibernateException saying
Database was not configured through Database method.
The link to show details was deactivated, so I couldn't get any further information. Searching for hours I finally found out that my connection string had an error ("pasword=xyz;" instead of "password=xyz;")
Try to set modifier protected in set_id and set_sampelList. for example:
public virtual int Id {
get; protected set;
}
and
public virtual IList<Store> StoresStockedIn {
get; protected set;
}
I begin receiving the
* Database was not configured through Database method.
error message while attempting to connect to a DB/2 database without having made any changes to my code. After verifying that the configuration file was being copied to the build directory and verifying that my XML was well-formed and conformed to version 2.2, I finally went to check the database to ensure that nothing had changed.
It turned out that the password for the connecting account had expired. It wasn't invalid nor was the account inactive--the password was merely expired. I am not sure why the expired password manifested in such an odd error message.
It seems like this error can be a bunch of different things. I got the same error and eventually figured out it was because I had excluded an unused view and mapping from the project. No idea how this was causing the error but as soon as I added it back the error was gone.

NHibernate.MappingException: No persister for: XYZ

Now, before you say it: I did Google and my hbm.xml file is an Embedded Resource.
Here is the code I am calling:
ISession session = GetCurrentSession();
var returnObject = session.Get<T>(Id);
Here is my mapping file for the class:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="HQData.Objects.SubCategory, HQData" table="SubCategory" lazy="true">
<id name="ID" column="ID" unsaved-value="0">
<generator class="identity" />
</id>
<property name="Name" column="Name" />
<property name="NumberOfBuckets" column="NumberOfBuckets" />
<property name="SearchCriteriaOne" column="SearchCriteriaOne" />
<bag name="_Businesses" cascade="all">
<key column="SubCategoryId"/>
<one-to-many
class="HQData.Objects.Business, HQData"/>
</bag>
<bag name="_Buckets" cascade="all">
<key column="SubCategoryId"/>
<one-to-many
class="HQData.Objects.Bucket, HQData"/>
</bag>
</class>
</hibernate-mapping>
Has anyone run to this issue before?
Here is the full error message:
MappingException: No persister for: HQData.Objects.SubCategory]NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName, Boolean throwIfNotFound)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:766 NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:752 NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Event\Default\DefaultLoadEventListener.cs:37 NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:2054 NHibernate.Impl.SessionImpl.Get(String entityName, Object id)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1029 NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1020 NHibernate.Impl.SessionImpl.Get(Object id)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:985 HQData.DataAccessUtils.NHibernateObjectHelper.LoadDataObject(Int32 Id)
in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQData\DataAccessUtils\NHibernateObjectHelper.cs:42 HQWebsite.LocalSearch.get_subCategory()
in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:17 HQWebsite.LocalSearch.Page_Load(Object sender, EventArgs e)
in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:27 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436
Update, here's what the solution for my scenario was: I had changed some code and I wasn't adding the Assembly to the config file during runtime.
Sounds like you forgot to add a mapping assembly to the session factory configuration..
If you're using app.config...
.
.
<property name="show_sql">true</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<mapping assembly="Project.DomainModel"/> <!-- Here -->
</session-factory>
.
.
Something obvious, yet quite useful for someone new to NHibernate.
All XML Mapping files should be treated as Embedded Resources rather than the default Content. This option is set by editing the Build Action attribute in the file's properties.
XML files are then embedded into the assembly, and parsed at project startup during NHibernate's configuration phase.
My issue was that I forgot to put the .hbm in the name of the mapping xml. Also make sure you make it an embedded resource!
I got this off of here:
In my case the mapping class was not public. In other words, instead of:
public class UserMap : ClassMap<user> // note the public!
I just had:
class UserMap : ClassMap<user>
Spending about 4 hours on googling and stackoverflowing, trying all of stuff around there, i've found my error:
My mapping file was called .nbm.xml instead of .hbm.xml. That was insane.
I had similar problem, and I solved it as folows:
I working on MS SQL 2008, but in the NH configuration I had bad dialect:
NHibernate.Dialect.MsSql2005Dialect
if I correct it to:
NHibernate.Dialect.MsSql2008Dialect
then everything's working fine without a exception "No persister for: ..."
David.
I had the same problem because I was adding the wrong assembly in Configuration.AddAssembly() method.
I was also adding the wrong assembly during initialization. The class I'm persisting is in assembly #1, and my .hbm.xml file is embedded in assembly #2. I changed cfg.AddAssembly(... to add assembly #2 (instead of assembly #1) and everything worked. Thanks!
To add to Amol's answer, don't make the mistake of specifying the Interface class type. Make sure you specify the implementation class. (Ie. don't use IDomainObjectType). Not that I made this mistake... :)
Should it be name="Id"? Typos are a likely cause.
Next would be to try it out with a non-generic test to make sure you're passing in the proper type parameter.
Can you post the entire error message?
This error occurs because of invalid mapping configuration. You should check where you set .Mappings for your session factory. Basically search for ".Mappings(" in your project and make sure you specified correct entity class in below line.
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<YourEntityClassName>())
If running tests on the repository from a seperate assembly, then make sure your Hibernate.cfg.xml is set to output always in the bin directory of said assembly. This wasn't happening for us and we got the above error in certain circumstances.
Disclaimer: This might be a slightly esoteric bit of advice, given that it's a direct result of how we structure our repository integration test assemblies (i.e. we have a symbolic link from each test assembly to a single Hibernate.xfg.xml)
Don't forget to specify mapping information in .config file
e.g.
where MyApp.Data is assembly that contains your mappings
Had a similar problem when find an object by id...
All i did was to use the fully qualified name in the class name. That is
Before it was :
find("Class",id)
Object so it became like this :
find("assemblyName.Class",id)
Make sure you have called the CreateCriteria(typeof(DomainObjectType)) method on Session for the domain object which you intent to fetch from DB.
I have a similar problem but all mentioned requirements are met. In my case I try to save some entity class (Type of OBJEKTE) back to the DB. Other places do work but only in this case it fails and raises this exception.
My solution (HACK) was to re-map the objet of type OBJEKTE again and store it then. Suddenly it works. But don't ask why.
OBJEKTE t = _mapper.Map<OBJEKTE>(inparam);
OBJEKTE res = await _objRepo.UpdateAsync(t);
If inparam would go straight to UpdateAsync() it cannot find a matching persistor.
It could be explained by the way NH does this. It derives a proxy from your mapping class and implements the properties with dirty handling included. See this:
t.GetType()
{Name = "OBJEKTE" FullName = "MyComp.Persistence.OBJEKTE"}
inparam.GetType()
{Name = "OBJEKTEProxyForFieldInterceptor" FullName = "OBJEKTEProxyForFieldInterceptor"}
The fun thing though is that the source of inparam is in fact the NH repository itself. Anyways. I stay with this reassign hack for the next time being.
I my case I fetched an entity without await:
var company = _unitOfWork.Session.GetAsync<Company>(id);
and then I tried to delete it:
await _unitOfWork.Session.DeleteAsync(company);
I could not decipher the error message that I'm deleting a Task<Company> instead of Company:
MappingException: No persister for: System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1+AsyncStateMachineBox'1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null],[NHibernate.Impl.SessionImpl+d__54`1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null]], NHibernate, Version=5.3.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4]]
You would think that after 14 years, all possible answers to this question have been written down. It seems like that is not the case.
In the application I'm currently working on, there are several ISessionFactory instances, each one for a different database.
If you're taking the wrong one to create your ISession, of course it will have no idea of the class you're trying to persist, which was the error in my case.

Categories

Resources