I'm trying to do a fairly simple insert using NHibernate into a SqlCe database, but it seems that NHibernate is generating wrong table name. It throws GenericADOException with the following details:
could not insert:
[WebLibrary.Models.Category#400a532d-f62e-4faf-978b-a29c00d4de46]
[SQL: INSERT INTO WebLibrary.Models_Categories (Title, Slug, DateCreated,
LastModified, CreatedBy, LastModifiedBy, ParentId, Id) VALUES (?, ?,
?, ?, ?, ?, ?, ?)]
Here is the mapping:
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping schema="WebLibrary.Models" assembly="WebLibrary" namespace="WebLibrary.Models" xmlns="urn:nhibernate-mapping-2.2">
<class name="Category" table="Categories">
<id name="Id" type="Guid">
<column name="Id" not-null="true" />
<generator class="guid.comb" />
</id>
...
</class>
</hibernate-mapping>
And here is the configuration:
var cfg = new Configuration();
cfg.DataBaseIntegration(c =>
{
c.Dialect<MsSqlCe40Dialect>();
c.ConnectionString =
"Data Source=|DataDirectory|\\library.sdf;Persist Security Info=False;";
})
.AddAssembly(typeof(NHibernateConfiguration).Assembly);
As you can see NHibernate is using the full qualified name of the class as the name of the table.
I'm using NHibernate 3.3.1.4000 with SqlCe 4.0.
What am I missing?
Your mapping contains a schema attribute. Remove that.
Adding a schema will prefix the table with the schema name.. which isn't required for tables in the default schema.
Related
Goal:
Make the stored procedure to be working with nhibernate.
Problem:
I retrieve an error message:
could not execute query
[ exec sp_retrieveAllProductList #p0 ]
Name:Produkt_kategori - Value:Dryck
[SQL: exec sp_retrieveAllProductList #p0]
What is the problem in the source code?
Info:
- Using VS 2013.
For AliasToBean to work, the returned column names (and their types) must match exactly the properties on the class to convert to.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="data_layer" namespace="data_layer">
<sql-query name="sp_retrieveAllProductList">
<return-scalar column="Produkt" type="string" />
<return-scalar column="Produkt_kategori" type="string" />
exec sp_retrieveAllProductList :Produkt_kategori
</sql-query>
</hibernate-mapping>
Never forget to change the column to the right value.
I am trying to map a SQL Server database with nHibernate that is full of tables with varchar primary keys that are generated by external software and I need update/read (no insert) access.
I cannot find a way to get past the following error:
XXXX.Tests.GMCRepository_Fixture.Can_get_existing_GMC_by_parameter'
failed: NHibernate.MappingException :
XXXX.Domain.Mappings.GMC2.hbm.xml(4,6): XML validation error: The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has invalid child element 'property' in namespace 'urn:nhibernate-mapping-2.2'. List of possible elements expected: 'meta, subselect, cache, synchronize, comment, tuplizer, id, composite-id' in namespace 'urn:nhibernate- mapping-2.2'.
Research has suggested this error is relating to there not being a valid primary key (id) defined.
Mapping XML looks like:
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping assembly="XXXX.Domain" namespace="XXXX.Domain" xmlns="urn:nhibernate-mapping-2.2" schema="GM.dbo">
<class name="GMC2" table="C2" lazy="true" >
<property name="PARAMETER">
<column name="PARAMETER" sql-type="varchar" not-null="true" />
</property>
...
<id name="Recid">
<column name="recid" sql-type="varchar" not-null="true" />
</id>
</class>
</hibernate-mapping>
Thanks for your help!
I believe that the convention is to have the ID mapping as the first thing under the class declaration.
Also as part of the Id mapping you need to specify the Generator of the ID. In your case I think you will need the assigned generator added to your ID mapping. Your class mapping will look something like this.
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping assembly="XXXXCRMAPI.Domain" namespace="XXXXCRMAPI.Domain" xmlns="urn:nhibernate-mapping-2.2" schema="GoldMine.dbo">
<class name="GMContact2" table="CONTACT2" lazy="true" >
<id name="Recid">
<generator type="assigned" />
<column name="recid" sql-type="varchar" not-null="true" />
</id>
<property name="Accountno">
<column name="ACCOUNTNO" sql-type="varchar" not-null="true" />
</property>
...
</class>
</hibernate-mapping>
Can Sqlite NHibernate id generator be made compatible with Postgresql? I'm planning to unit test my NHibernate Postgresql project based on this http://ayende.com/Blog/archive/2009/04/28/nhibernate-unit-testing.aspx
If there is no compatible id generator, is there a way to signal NHibernate to ignore id generator when it is using different dialect?
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" assembly="RuntimeNhibernate" namespace="RuntimeNhibernate" >
<class name="Blog" table="blog">
<id name="BlogId" column="blog_id">
<!-- can this be ignored when using different dialect.. -->
<generator class="sequence">
<param name="sequence">blog_id_seq</param>
</generator>
<!-- ...can this -->
</id>
<property name="AllowsComments" column="allows_comments"/>
<property name="CreatedAt" column="created_at"/>
<property name="Subtitle" column="subtitle"/>
<property name="Title" column="title"/>
</class>
</hibernate-mapping>
Error when using Sqlite dialect on Postgresql-specific mapping:
NHibernate.MappingException: could not instantiate id generator: sequence --->
NHibernate.MappingException: Dialect does not support sequences
My suggestion is that you use a DB-agnostic generator, like HiLo.
I have Canine and CanineHandler objects in my application. The CanineHandler object has a PersonID (which references a completely different database), an EffectiveDate (which specifies when a handler started with the canine), and a FK reference to the Canine (CanineID).
Given a specific PersonID, I want to find all canines they're currently responsible for. The (simplified) query I'd use in SQL would be:
Select Canine.*
from Canine
inner join CanineHandler on(CanineHandler.CanineID=Canine.CanineID)
inner join
(select CanineID,Max(EffectiveDate) MaxEffectiveDate
from caninehandler
group by CanineID) as CurrentHandler
on(CurrentHandler.CanineID=CanineHandler.CanineID
and CurrentHandler.MaxEffectiveDate=CanineHandler.EffectiveDate)
where CanineHandler.HandlerPersonID=#PersonID
Edit: Added mapping files below:
<class name="CanineHandler" table="CanineHandler" schema="dbo">
<id name="CanineHandlerID" type="Int32">
<generator class="identity" />
</id>
<property name="EffectiveDate" type="DateTime" precision="16" not-null="true" />
<property name="HandlerPersonID" type="Int64" precision="19" not-null="true" />
<many-to-one name="Canine" class="Canine" column="CanineID" not-null="true" access="field.camelcase-underscore" />
</class>
<class name="Canine" table="Canine">
<id name="CanineID" type="Int32">
<generator class="identity" />
</id>
<property name="Name" type="String" length="64" not-null="true" />
...
<set name="CanineHandlers" table="CanineHandler" inverse="true" order-by="EffectiveDate desc" cascade="save-update" access="field.camelcase-underscore">
<key column="CanineID" />
<one-to-many class="CanineHandler" />
</set>
<property name="IsDeleted" type="Boolean" not-null="true" />
</class>
I haven't tried yet, but I'm guessing I could do this in HQL. I haven't had to write anything in HQL yet, so I'll have to tackle that eventually anyway, but my question is whether/how I can do this sub-query with the criterion/subqueries objects.
I got as far as creating the following detached criteria:
DetachedCriteria effectiveHandlers = DetachedCriteria.For<Canine>()
.SetProjection(Projections.ProjectionList()
.Add(Projections.Max("EffectiveDate"),"MaxEffectiveDate")
.Add(Projections.GroupProperty("CanineID"),"handledCanineID")
);
but I can't figure out how to do the inner join. If I do this:
Session.CreateCriteria<Canine>()
.CreateCriteria("CanineHandler", "handler", NHibernate.SqlCommand.JoinType.InnerJoin)
.List<Canine>();
I get an error "could not resolve property: CanineHandler of: OPS.CanineApp.Model.Canine". Obviously I'm missing something(s) but from the documentation I got the impression that should return a list of Canines that have handlers (possibly with duplicates). Until I can make this work, adding the subquery isn't going to work...
I've found similar questions, such as Only get latest results using nHibernate but none of the answers really seem to apply with the kind of direct result I'm looking for.
Any help or suggestion is greatly appreciated.
Joining to a derived table, CurrentHandler in your example, won't work in HQL the last time I checked. Try mapping a stored procedure that lets you write whatever SQL you like. Here's what a mapped stored procedure looks like:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="S2.BP.NHSupport" namespace="S2.BP.Model">
<sql-query name="spGoGetMyDogs" callable="true">
<return-scalar column="PersonID" type="int" />
exec spGoGetMyDogs #PersonID=:personID
</sql-query>
</hibernate-mapping>
Then you can pass your PersonID parameter in and have NH map the results back to your objects with a transformer like so:
public IEnumerable<Canine> LetTheDogsOut(int personID) {
return nhSession.GetNamedQuery("spGoGetMyDogs")
.SetInt32("personID", personID)
.SetResultTransformer(Transformers.AliasToBean(typeof(Canine)))
.List<Canine>();
}
I'm trying to solve pretty easy problem. I want to establish connection to 2 totally different databases ( but both mysql ). Now I tried to solve this by creating multiple config files and then creating multiple sessions. Everything works until I reached relations.
I have 2 tables in 2 databases:
db1
- News
db2
- News_Authors
I added News to db1 config and News_Authors to db2 config. When I try to build simple one-to-one relation error, I receive:
An association from the table songs refers to an unmapped class: db1.News_Authors
News.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="project.News, project" table="news" lazy="false">
<id name="id" column="id" type="integer" length="11">
<generator class="native" />
</id>
<property name="title" type="String" length="255" />
<property name="authorid" type="integer" length="5" />
<one-to-one name="NewsAuthor" cascade="all-delete-orphan" lazy="proxy" column="authorid" unique="true" />
</class>
</hibernate-mapping>
News_Authors.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="project.News_Authors, project" table="news_authors" lazy="false">
<id name="id" column="id" type="integer" length="11">
<generator class="native" />
</id>
<property name="name" type="String" length="255" />
</class>
</hibernate-mapping>
config
I added this to enable mappings. Now If I set both in one config files, everything works...
<mapping resource="project.News.hbm.xml" assembly="project" />
So how could I during creating of session also "notify" nhibernate that I have multiple sessions? Or should I pick totally another approach?
One other possible solution would be to create views in one of the sql server databases to reference the tables in the other. Views map just like tables and its easy to do a view that returns something like:
select * from db2.News_Authors
in the db1 database.
this way you would only need a single .hbm.xml file that maps to one of the two databases.
Hope this helps,
-Max
What you are after is not multiple sessions but multiple session factories. See this for more details.
The key here is that you don't have to initialize your session factory through config file - you can do it programatically. And it's just a step to have two session factories.