Fluent NHibernate - exception occurred during configuration of persistence layer - c#

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.

Related

Entity Framework Error unable to load the specified metadata resource [duplicate]

This question already has answers here:
MetadataException: Unable to load the specified metadata resource
(47 answers)
Closed 6 years ago.
Yes I did read and try entity framework Unable to load the specified metadata resource
I typically use code first and have had no issues. However I needed to troubleshoot a project with EDMX
Context:
public partial class x500Entities : DbContext
{
public x500Entities()
: base("name=x500Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<WorkerPublicExtended> WorkerPublicExtendeds { get; set; }
}
connection string :
<add name="x500Entities"
connectionString="metadata=res://*/CDISWorkerPublicExtended.csdl|res://*/CDISWorkerPublicExtended.ssdl|res://*/CDISWorkerPublicExtended.msl;provider=System.Data.SqlClient;provider connection string="data source=xserver;initial catalog=x500;persist security info=True;user id=xuser;password=xpassword;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient"/>
ERROR :
An exception of type 'System.Data.Entity.Core.MetadataException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Unable to load the specified metadata resource.
Upon hitting this line:
return context.WorkerPublicExtendeds.FirstOrDefault(x => x.upperIDSID == idsid.ToUpper().Trim());
Complete Method :
public WorkerPublicExtended GetEmployee(string idsid)
{
using (x500Entities context = new x500Entities())
{
return context.WorkerPublicExtendeds.FirstOrDefault(x => x.upperIDSID == idsid.ToUpper().Trim());
}
}
Why is this happening?
I connected to sql server ssms and I don't see the table WorkerPublicExtended that I have seen in diagram edmx and the model, I don't see where that name is translated to a real table name. How is this?
Probable causes:
1) your resource file is nowhere to be found in you project (this resource file is configured in you app.config in connection string) confirm oyu have it.
2) when you say you connect to the database and you don't see the Table then you're in the wrong database? that should never happen, you have an EDMX generated for another database, or someone droped the table and didn't regenerate the edmx ? :X
If you have 200% sure that the database you are connecting it's the latest in schema, procedures, views, etc, or it's the production database, why not to delete the entire edmx and recreate, test and redeploy?
The three parts of the EMDX look correct in the connection string. After double-checking this part to be correct (refer to this guideline to troubleshoot your issue):
You might have changed the MetadataArtifactProcessing property of the model to Copy to Output Directory, or
You changed other things (like the name of an assembly), or
You might be using a post-compile task to embed EMDX which is no longer working.
Source from here.
Also check the entire string for correct syntax.

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

Application can't scaffold items

I created an MVC 5 application in VS 2013 Professional and then used EF 6.1 code first with an existing DB on SQL Server Express. When I try to create the views I’m using the “New scaffolded item…” then selecting the “MVC 5 controller with views, using Entity Framework.” I select the model and context classes and click OK. Then the following error message appears and no code is created. I’ve uninstalled EF Power Tools with the same error.
Error
There was an error running the selected code generator: ‘Exception has
been thrown by the target of an invocation.’
I've also tried uninstalling/reinstalling VS 2013 and SQL Server with no changes.
Any other ideas about what might cause this error?
In my case I moved my connection strings out of the Web.config to
<connectionStrings configSource="ConnectionStrings.config"/>
that when I started getting the error when I was trying to scaffold.
There was an error running the selected code generator: ‘Exception has been thrown by the target of an invocation.’
Moving my connection strings back to the Web.config solved my issue.
I had this problem too,
I solved the problem by calling the base.onModelCreating in my DB context
base.OnModelCreating(modelBuilder);
I had faced the same problem while creating controller using scaffold with 'ASP.NET MVC5 using views with Entity Framework'
The problem was because I provided <connectionStrings> tag before <configSections> in web.config. setting <connectionStrings> after <configSections> resolved the issue.
I guess, while scaffolding, ASP.NET MVC want to resolve the Entity Framework first, then the connection string, as I have provided connection string earlier so that after resolving the Entity Framework version it could not find the connection string so it thrown invocation problem.
This solved the issue for me,
Adding throwIfV1Schema: false to base of DbContext
As so:
public MyDbContext() : base("ConectionStringName", throwIfV1Schema: false) { }
Late reply; but, I am posting this answers with the hope that somebody can use this answer to solve their problem.
For some reason, if your program CANNOT read connectionString information (either from web.config or from other means) then, this error will be thrown.
Make sure that valid connectionString information is being retrieved properly without any problem.
I had the same error message.
I tried adding a new Data context class from the Add Controller dialog, and then I got a different error:
There was an error running the selected code generator:
'Sections must only appear once per config file. See the help topic
<locations> for exceptions.
It turns out that I had two <connectionStrings> elements in my web.config file. (I had pasted one from the app.config of the class library that contained my Entity Framework model.)
In my case, I had to revert my DBContext constructor to just using a static connection string, as defined in web.config
Scaffolding did not work when I used a dynamically created connection string.
public MyContext() : base("name=MyContext") { }
I had the same problem where it wouldn't add scaffold items it seems that uninstalling entity-framework through the nuget package manager console works
To Run Package Manager Console :
Tools -> NuGet Package Manager -> Package Manager Console
To Remove:
UnInstall-Package EntityFramework
To Reinstall:
Install-Package EntityFramework
Or in one command:
Update-Package -reinstall EntityFramework
I hope this can help someone as it took me a while to come to this.
This may help resolve your error.
In my OnModelCreating i was doing this for each entity:
modelBuilder.Configurations.Add(new EntityTypeConfiguration<EntityModel>);
When i changed it to the following i stopped getting the error you are receiving.
modelBuilder.Entity<EntityModel>();
I tried most of the above without luck.
What finally worked was:
Delete the previously dynamically created string entry
Delete my model (keeping all controllers and views)
Recreate the ADO.NET Entity Data Model - using the same name, creating a new connection string entry with the same name as before
Then everything worked again, minus 3 hours of development time.
re-add (from a backup) all of my property attributes to the table/entity classes
Seems to have something to do with the dynamically created connection string and the model. Would appreciate any thoughts on what could have happened.
In my case, I solved the issue with the connection string in the web.config.
Previuos the issue I has
<connectionStrings configSource="Configs\ConnectionString.config"/>
and I doesnt know why, but vs cant connect to the database and fail.
after the change
<connectionStrings>
<add name="UIBuilderContext" connectionString="metadata=res:/ ..... " />
</connectionStrings>
and it works
My solution was as simple as changing back the connection string name in my Web Config to DefaultConnection. Even though my dbContext has another name!
Took me 2 hours to find out this nonsense!
It seems a problem of connecting setting / inconsistent entry in via Web.config.
To fix this issue , follow below steps:
Remove connection related information (staring with <connectionStrings> from Web.config and remove models generated so far.
Now generate the model and it will add fresh connection entry in Web.config file. Once model is generated, build the solution then start doing Scaffolding controlled. it will work.
I ran into this problem too using VS 2015. I tried all the other solutions here to no success. It turned out that my connection string (although formed exactly how MS tells us to form it) needed double \ to work properly.
Here is what it was that was NOT working:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\V11.0;AttachDbFilename=|DataDirectory|\SquashSpiderDB.mdf;Initial Catalog=SquashSpiderDB;Integrated Security=True" providerName="System.Data.SqlClient" />
and here is what I changed it to in order to get the code generator to work:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\\V11.0;AttachDbFilename=|DataDirectory|\SquashSpiderDB.mdf;Initial Catalog=SquashSpiderDB;Integrated Security=True" providerName="System.Data.SqlClient" />
Notice the double \ characters in front of V11.0 and the database name.
Hope this saves somebody else some time.
UPDATE
This gets the code generation to work, but then the app won't run because the \V11.0 isn't a valid connection string. This looks to me like MS has a bug in their code generation when it parses the connection string. I had to change it back to a single \ after I ran the code generation to get the app working again.
UPDATE 2
After some more digging by my partner, we found out that what was really screwing up code generation was the fact that we had changed the "Initial Catalog" field. When the project was created by the Wizard, it automatically set the Initial Catalog to aspnet--. We had then changed this Initial Catalog field to be DB. This worked great for the application running. It could get to the database just fine. But for some reason this screws up the code scaffolding generation. By putting the Initial Catalog back to what it was before (the aspnet--, the scaffolding started to work again (without needing the \V11.0).
Hope that helps somebody in the future.
Check relationships between entities or other model design problem. For testing, create new class model without no relationship and use Scaffold to generate controllers and views.
Works for me.
I was getting the same error when I made some changes to my model .. Only way I was able to resolve was
1) stop/kill the process
2) clean solution and rebuild the solution
If by any chance you are following "Getting Started with Entity Framework 6 Code First using MVC 5" by Tom Dykstra.
I doubled check everything and my connection string is perfect. What I failed to realize was I copied another set of appSettings which I already have. Look below
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
My advice is to check every inch of Web.config and I'm sure that is the culprit.
In my case NuGet added the following provider to the web.config:
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact"/>
When I changed the provider to
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
It solved the problem (costed me about 5 hours though to figure it out :-( )
I Had the same error. Here are the two things I did to fix the problem:
Added name to base in my context:
base("name=connectionstringname")
I made a mistake in myconnection string and fixed it.
It is (I'm 99% positive) a connection string issue. Once i fixed the issue in Web.Config the error went away. I was using DB first, in another project and once I copied the DB first connection string from the App.config into the web.config (using the same name) it worked as expected.
Using Visual Studio 2015
Upgraded mysql server and in the process the mysql for visual studios was upgraded from 6.9.7 to 6.9.8
In my web config there was still a reference to the old 6.9.7 version
Here is my git diff that solved the issue:
- <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices,MySql.Data.Entity.EF6,Version=6.9.7.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d"></provider>
+ <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices,MySql.Data.Entity.EF6,Version=6.9.8.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d"></provider>
I realize this question is old now, but I thought I'd post what solved my issue in case it helps anyone later on. In my case, it was a combination of several things mentioned in other answers. To secure my connection string I had...
Moved the connection string out of the Web.config file
Moved the server name and password to a separate file referenced in the AppSettings portion of Web.config
Used a SqlConnectionStringBuilder to put the elements together and then pass it to my context class constructor
After doing this, I was unable to create any more controllers. To fix the issue, I had to ...
Put the complete connection string back in Web.config AND remove the reference to the external connection string file
Add a parameterless constructor to my context class and give it the name of my connectionString like this:
public contextClass() : base("name=connectionStringName") { }
Rebuild the solution, and create the controller again, and it worked!
everyone. I know I'm a little late, but I think that is still valid to share my experience with this problem.
I faced this message in two projects and in both cases the problem was with the connection string.
In the first case it was "InitialCatalog" instead of "Initial Catalog" (separated).
In the second case the server name (Data Source param) was wrong.
I hope it helps.
Best regards.
For some reason when I comment the oracle.manageddataaccess.client section out between <configSections> in web.config, it worked. (VS 2015 and ODT 12)
<configSections>
<section name="entityFramework" type" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<!--<section name="oracle.manageddataaccess.client" />-->
</configSections>
In my case, the problem was caused by an external app settings file:
<appSettings configSource="appSettings.config" />
Bringing the app settings back into the web.config file resolved the issue.
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
I had this:
<appSettings configSource="App_Config\Server\AppSettings.config" />
<connectionStrings configSource="bin\Connections.config" />
I had to remove BOTH AND put back.
<connectionStrings>
<add name="UIBuilderContext" connectionString="metadata=res:/ ..... " />
</connectionStrings>
Removing just still caused the same error.
Using: VS 2015 Community Edition and EF 6.1.3
Implemented also: Seed method, with a personalized class, and configured in the web.config file to run every time that the model changes.
This seems to be related to some misconfiguration in the web.config file, in my case, like some of the cases I see in this post with other sections of the file, the section was repeated with different content, but it's repeated the main tag of course. The case of the section out of place, over the section, is also cause of the same behavior and narrow message while try to scaffold.
Your context class might be throwing an exception.
I was following along in the book "C# 6.0 and the .NET 4.6 Framework" and one of the last exercises of the data access layer section was to add logging. Well, I guess that blows up the scaffold wizard. Probably file permissions on sqllog.txt or HttpRuntime is not defined...who knows. When I commented all this stuff out, it worked again.
namespace AutoLotDAL.EF
{
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.Interception;
using AutoLotDAL.Interception;
using AutoLotDAL.Models;
using System;
using System.Data.Entity.Core.Objects;
using System.Web;
public class AutoLotEntities : DbContext
{
//static readonly DatabaseLogger databaseLogger =
// new DatabaseLogger($"{HttpRuntime.AppDomainAppPath}/sqllog.txt", true);
public AutoLotEntities()
: base("name=AutoLotConnection")
{
////DbInterception.Add(new ConsoleWriterInterceptor());
//databaseLogger.StartLogging();
//DbInterception.Add(databaseLogger);
//// Interceptor code
//var context = (this as IObjectContextAdapter).ObjectContext;
//context.ObjectMaterialized += OnObjectMaterialized;
//context.SavingChanges += OnSavingChanges;
}
//void OnObjectMaterialized(object sender,
// System.Data.Entity.Core.Objects.ObjectMaterializedEventArgs e)
//{
//}
//void OnSavingChanges(object sender, EventArgs eventArgs)
//{
// // Sender is of type ObjectContext. Can get current and original values,
// // and cancel/modify the save operation as desired.
// var context = sender as ObjectContext;
// if (context == null)
// return;
// foreach (ObjectStateEntry item in
// context.ObjectStateManager.GetObjectStateEntries(
// EntityState.Modified | EntityState.Added))
// {
// // Do something important here
// if ((item.Entity as Inventory) != null)
// {
// var entity = (Inventory)item.Entity;
// if (entity.Color == "Red")
// {
// item.RejectPropertyChanges(nameof(entity.Color));
// }
// }
// }
//}
//protected override void Dispose(bool disposing)
//{
// DbInterception.Remove(databaseLogger);
// databaseLogger.StopLogging();
// base.Dispose(disposing);
//}
public virtual DbSet<CreditRisk> CreditRisks { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Inventory> Inventory { get; set; }
public virtual DbSet<Order> Orders { get; set; }
}
}
EF 6.1 does not Support scaffolding template use EF 5
Chares

NHibernate unable to create SessionFactory

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

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