I'm a newbie to NHibernate and trying to get my first app working with NHibernate + SQLite - In memory DB.
so far, I've done the following,
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<reflection-optimizer use="true"/>
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SQLite20Driver</property>
<property name="connection.connection_string">"Data Source=:memory:;Version=3;New=True;"</property>
<property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
<property name="connection.release_mode">on_close</property>
<property name="query.substitutions">true=1;false=0</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
Hibernate.cs
public NHibernate.ISessionFactory Hibernate()
{
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
cfg.Configure(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "hibernate.cfg.xml"));
cfg.AddAssembly(System.Reflection.Assembly.GetExecutingAssembly());
var sessionFactory = cfg.BuildSessionFactory();
return sessionFactory;
}
Now when I call Hibernate() function, the following line throws an exception,
var sessionFactory = cfg.BuildSessionFactory();
Exception :
System.ArgumentException: 'Data Source cannot be empty. Use :memory: to open an in-memory database'
I've been trying to fix this for quite some time now, I have tried with different connection strings, but I've had no luck. Any suggestions/guidance would be much appreciated.
Many thanks.
I doubt there should be double quotes around the value of the connection string property in the configuration file.
Related
I am having some problem configuring NHibernate to retrieve data in my MVC 4 application.
To keep things simple I have configured all code in the Index method.
Here is code for my Category controller :
and here is my configuration in web.config :
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="NHibernate.Test">
<property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver
</property>
<property name="connection.connection_string">
Data Source=.;Initial Catalog=UsingNH;uid=myuid;Password=mypwd
</property>
<property name="adonet.batch_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="use_outer_join">true</property>
<property name="command_timeout">60</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<property name="proxyfactory.factory_class">
NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
</property>
</session-factory>
</hibernate-configuration>
Mapping file for Category is
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="nhibernate-mapping-2.2" namespace="UsingNHibernate.Models" assembly="UsingNHibernate">
<class name="Category" table="Categories" lazy="false">
<id name="Id" columnId="Id" unsaved-value="0">
<generator class="native" />
</id>
<property name="Name">
<column name="Name" data-type="varchar(50)" not-null="true" />
</property>
</class>
</hibernate-mapping>
and the Category table schema is
CREATE TABLE [dbo].[Categories](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
CONSTRAINT [PK_Category] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
) ON [PRIMARY]
The problem is that the program compiles and runs well but does not return any category.
The code
var lst = (List<Category>)criterion.List<Category>();
returns 0 items (verified in debugger).
Is there any problem in my configuration or Mapping files?
Comment if additional info is required.
Thanks.
If no mappings are defined, nhibernate will simply fail silently and return an empty list if you query a list of entities.
I guess you do not copy over the mapping files to your bin directory. Mark the mapping files to be copied (via properties).
I changed the Build Action Property of the hbm mapping file to Embedded Resource,
then I can get the data.
(It's same way as the OP's comment, but I post it as an answer to be easier noticed.)
How to write correct connection string for Nhibernate using SQL Server 2012?
Should I write also database name?
Error:
I get error with wrong „initial catalog”
Wrong connection string for NHibernate (I copy this connection string from my server):
<?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.MsSqlCeDialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlServerCeDriver</property>
<property name="connection.connection_string">Data Source=RAFAL-KOMPUTER\MSSQLSERVER4;Initial Catalog=rafal;Integrated Security=True</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
I copy connection string from this part:
I am trying also this but does not help.
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=RAFAL-KOMPUTER\MSSQLSERVER4;Initial Catalog=rafal;Integrated Security=True</property>
I don`t know how correct configure for SQL Server 2012
The first snippet should not work, while the driver is for CE (Compact edition).
The second one looks better, and even more it is working for me. (see more here http://www.connectionstrings.com/sql-server-2012). The most important thing, is to have correct settings of the Provider name (check here: https://stackoverflow.com/a/8150792/315850). Try this adjusted snippet (just to be sure that all parts are set correctly)
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<!-- to profit from features in 2012, use its dialect -->
<property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<!-- the simplest connection string -->
<property name="connection.connection_string">Data Source=RAFAL-KOMPUTER\MSSQLSERVER4;Database=rafal;Trusted_Connection=True;</property>
We have to be sure that correct driver is used (not CE or any other then NHibernate.Driver.SqlClientDriver which means System.Data.SqlClient)
Double check that your 1) SQL server and named instance is: RAFAL-KOMPUTER\MSSQLSERVER4 and 2) the Database name is: rafal and 3) your login has access rights to it, this must work
just replace : SqlServerCeDriver by SqlClientDriver as below :
Replace : <property name="connection.driver_class">NHibernate.Driver.SqlServerCeDriver</property>
By: <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
I have a simple app that uses a sqlite db in my data layer, nothing major. I have populated a few records for UI testing, but I can't pull the data back at all.
The thing is that my my unit tests are able to CRUD without fail, but I'm concerned that something isn't right when I simply want to select all records from a table like to populate a gridview.
I'm using NHibernate for the first time in a loooooong time so I can't tell if this s setup issue or something else.
Base selection method:
protected IList<T> SelectMultipleInternalALL()
{
// create session and select.
using (ISession session = NBHelper.OpenSession())
return session.CreateCriteria<T>().List<T>();
}
Helper class:
public class NBHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
var configuration = new Configuration();
configuration.Configure();
configuration.AddAssembly(Assembly.GetCallingAssembly());
new SchemaExport(configuration).Execute(false, true, false);
_sessionFactory = configuration.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
Table config:
<class name="UserData" table="User">
<id name="Id" type="System.Int32" column="Id" >
<generator class="native"/>
</id>
<property name="Email" />
<property name="FirstName" />
<property name="LastName" />
<property name="Notes" />
<property name="Favorite" type="boolean" />
<bag name="Addresses" inverse="true" cascade="all" generic="true">
<key column="UserId" />
<one-to-many class="AddressData"/>
</bag>
<bag name="Tags" inverse="true" cascade="all" generic="true">
<key column="WhatId" />
<one-to-many class="TagData"/>
</bag>
NHibernate config:
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SQLiteDriver</property>
<property name="connection.connection_string">
Data Source=C:\Documents and Settings\bryang\Desktop\AddressBook\AddressBook.DAL\addressbook.s3db
</property>
<property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
<property name="query.substitutions">true=1;false=0</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<property name="show_sql">true</property>
The database location is totally valid, but I get no records. I think the issue might be in the CreateCriteria() call but my unit tests are 100% able to insert and read back the data. I'm missing something and I can't figure out what.
EDIT
I was also running into a lazy loading exception from my one-to-many relationships. I made the collection columns lazy="false" which cleared up the error. A side-effect is that now I return data everywhere, but it's unit test data from somewhere and when I open the sqlite db I still only see where my small set of data was created. Where is this data being held on to? I'm not managing my ISession manually, and I'm even flushing after simple things like a select. Where on earth is this data coming from?
At this point I'll take some data over none, but it makes no sense to me if the db file I'm looking at has nothing in it. Thanks,
Bryan
First of all, change the Driver to the newer version of the driver, the SQLiteDriver is for the old finstar driver, and it has some quirks with the newer version of SQL Lite. Also, your database path needs to be changed, you can't reference a path with spaces without putting "'s around it. If you put your database in the same directory as your executable, you can just use the db name. This configuration works great for me :
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SQLite20Driver</property>
<property name="connection.connection_string">Data Source=core.db3;Version=3</property>
<property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
<property name="query.substitutions">true=1;false=0</property>
<property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<property name="show_sql">true</property>
I'm doing a project in Nhibernate with MySql in asp.net. In that while executing the code I got the error like
An exception occurred during configuration of persistence layer
in the below line
ISessionFactory factory = new NHibernate.Cfg.Configuration().Configure).BuildSessionFactory();
So let me help to trouble shoot the error.
Here s my Configuration file
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<!-- an ISessionFactory instance -->
<session-factory>
<!-- properties -->
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider
</property>
<property name="connection.driver_class">
NHibernate.Driver.MySqlDataDriver
</property>
<property name="connection.connection_string">
Server=localhost;Database=hrms;User ID=test;Password=test;
</property>
<property name="dialect">NHibernate.Dialect.MySQL5Dialect</property>
<property name="show_mysql">true</property>
<!-- mapping files -->
<mapping resource="WebApp1.Job.hbm.xml" assembly="WebApp1" />
</session-factory>
</hibernate-configuration>
Incomplete configuration perhaps? Try manual configuration initialization like the following:
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
cfg.SetProperty("dialect", "NHibernate.Dialect.MySQLDialect");
cfg.SetProperty("connection.driver_class", "NHibernate.Driver.MySqlDataDriver");
cfg.SetProperty("connection.connection_string", "Server=YourServer;Database=YourDatabase;User ID=YourId;Password=YourPass;CharSet=utf8");
cfg.SetProperty("proxyfactory.factory_class", "NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu");
cfg.AddAssembly("Your.Assembly.Name");
ISessionFactory sessionFactory = cfg.BuildSessionFactory();
If everything works, move it to XML if you like.
Please read the inner exception that is being thrown and it's very likely you would know the cause. In my experience it can be as simple as the code is looking for the hibernate.cfg.xml file in bin/debug and could not find it.
I had a similar problem. Problem was that I used in Web.config:
<section name="nhibernate" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
<nhibernate xmlns="urn:nhibernate-configuration-2.2">
.
.
.
</nhibernate>
instead of:
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
.
.
.
</hibernate-configuration>
I couldn't figure out why NHibernate is doing this.
Here's part of my table in MS SQL
CREATE TABLE Person (
nameFamily text,
nameGiven text
)
Here's Person.hbm.xml
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Infosci.Dpd.Model.Person,Infosci.Dpd.Model" table="Person" lazy="true">
<property type="string" name="NameGiven" column="nameGiven" />
<property type="string" name="NameFamily" column="nameFamily" />
</class>
</hibernate>
And in my Person.cs I name my property like the following
string NameFamily
{
get ;
set ;
}
string NameGiven
{
get ;
set ;
}
Then I try to create a record using the following code
ISession session = NHibernateHelper.GetCurrentSession();
Person person = new Person();
person.NameFamily = "lee";
session.Save(person);
And what's weird is when I try do execute it, NHibernate actually change the column name by doing the following
NHibernate: INSERT INTO Person (name_family,name_given.......
So here NHibernate chagne my column name from NameFamily to name_family although I did specify the column name.
Is this a NHibernate bug? Or is there any configuration I need to do?
And here's my hibernate config file
<?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.MsSql2000Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=xxxxxxx;Initial Catalog=xx;Integrated Security=True;Pooling=False;User ID=xxxx;Password=xxxx</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
And this is how I create the sessionFactory
sessionFactory = new `Configuration().Configure("hibernate.cfg.xml").
SetNamingStrategy(ImprovedNamingStrategy.Instance).
AddFile("Person.hbm.xml").
BuildSessionFactory();`
That's a "feature" of SetNamingStrategy(ImprovedNamingStrategy.Instance)
It will add underscores before each uppercase letter in mixed-cased names.
Not sure how you disable it (me not being a nhibernate user)
What I end up doing is just use the default naming strategy or SetNamingStrategy(DefaultNamingStrategy.Instance)
the default naming strategy will leave mix-cased name untouched