OracleDataClientBatchingBatcherFactory Throws Null Reference Exception - c#

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

Related

Dapper error: Could not load type 'Dapper.SqlMapper'

I'm new in Dapper. I trying to create new project and map local database by Dapper. Unfortunately I always receive this error:
Could not load type 'Dapper.SqlMapper' from assembly 'Dapper,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
I added Dapper by NuGet (Dapper v. 1.39.0.0). This is example of my code:
public static IEnumerable<TBMobileDetails> Allmobilelisting()
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=""c:\users\database.mdf"";Integrated Security=True");
string query = "select * from Mobiledata";
var result = con.Query<TBMobileDetails>(query);
return result;
}
Where is the problem?
This problem occurs generally when there is an object / class / type named
Dapper
dapper
Do following steps to remove this issue
Create a Fresh Project and do NOT name anything in it with Dapper (case insensitive). Even if you change name of exiting 'dapper' object in your existing project then too it might create problems so its better to create a fresh project! I think it has something to do with assembly or hardcoding somewhere in dapper or visual studio (not sure!).
Use Nuget Manager again to Install Dapper.
It should work fine now.
My problem was that there was a namespace collision. Maybe a little obvious, but don't name anything "dapper" in your project.

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

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