I'm using nhibernate to store some user settings for an app in a SQL Server Compact Edition table.
This is an excerpt the mapping file:
<property name="Name" type="string" />
<property name="Value" type="string" />
Name is a regular string/nvarchar(50), and Value is set as ntext in the DB
I'm trying to write a large amount of xml to the "Value" property. I get an exception every time:
#p1 : String truncation: max=4000, len=35287, value='<lots of xml..../>'
I've googled it quite a bit, and tried a number of different mapping configurations:
<property name="Name" type="string" />
<property name="Value" type="string" >
<column name="Value" sql-type="StringClob" />
</property>
That's one example. Other configurations include "ntext" instead of "StringClob". Those configurations that don't throw mapping exceptions still throw the string truncation exception.
Is this a problem ("feature") with SQL CE? Is it possible to put more than 4000 characters into a SQL CE database with nhibernate? If so, can anyone tell me how?
Many thanks!
Okay, with many thanks to Artur in this thread, here's the solution:
Inherit from the SqlServerCeDriver with a new one, and override the InitializeParamter method:
using System.Data;
using System.Data.SqlServerCe;
using NHibernate.Driver;
using NHibernate.SqlTypes;
namespace MySqlServerCeDriverNamespace
{
/// <summary>
/// Overridden Nhibernate SQL CE Driver,
/// so that ntext fields are not truncated at 4000 characters
/// </summary>
public class MySqlServerCeDriver : SqlServerCeDriver
{
protected override void InitializeParameter(
IDbDataParameter dbParam,
string name,
SqlType sqlType)
{
base.InitializeParameter(dbParam, name, sqlType);
if (sqlType is StringClobSqlType)
{
var parameter = (SqlCeParameter)dbParam;
parameter.SqlDbType = SqlDbType.NText;
}
}
}
}
Then, use this driver instead of NHibernate's in your app.config
<nhibernateDriver>MySqlServerCeDriverNamespace.MySqlServerCeDriver , MySqlServerCeDriverNamespace</nhibernateDriver>
I saw a lot of other posts where people had this problem, and solved it by just changing the sql-type attribute to "StringClob" - as attempted in this thread.
I'm not sure why it wouldn't work for me, but I suspect it is the fact that I'm using SQL CE and not some other DB. But, there you have it!
<property name="Value" type="string" />
<column name="Value" sql-type="StringClob" />
</property>
I'm assuming this is a small typo, since you've closed the property tag twice. Just pointing this out, in case it wasn't a typo.
Try <property name="Value" type="string" length="4001" />
Tried:
<property name="Value" type="string" length="4001" />
and
<property name="Value" type="string" >
<column name="Value" sql-type="StringClob" length="5000"/>
</property>
Neither worked, I'm afraid... Same exception - it still says that the max value is 4000.
Why are you using the sub-element syntax?
try:
<property name='Value' type='StringClob' />
On my current deplyoment of SQL CE and NHibernate I use a length of 4001. Then NHibernate generates the stuff as NTEXT instead of NVARCHAR.
Try that.
Another thing to use with NHibernate and SQL CE is:
<session-factory>
...
<property name="connection.release_mode">on_close</property>
</session-factory>
That solves some other problems for me atleast.
After reading your post this modification got it working in my code
protected override void InitializeParameter(IDbDataParameter dbParam,string name,SqlType sqlType)
{
base.InitializeParameter(dbParam, name, sqlType);
var stringType = sqlType as StringSqlType;
if (stringType != null && stringType.LengthDefined && stringType.Length > 4000)
{
var parameter = (SqlCeParameter)dbParam;
parameter.SqlDbType = SqlDbType.NText;
}
}
Related
I have the following class:
public class Foo
{
//...
protected int? someData;
public int? SomeData
{
get {return someData;}
set {someData = value;}
}
//...
}
This class is mapped in HBM file:
<class name="Foo" table="Foo">
//....
<property name="someData" access="field" column="SOME_DATA" />
//....
</class>
For legacy reasons, the columns were mapped to a fields (lowercase), which are unaccessible (not public properties - uppercase).
These lowercase mappings are using multiple times in the project as part of HQL strings, criteria-based queries and so on. It is close to impossible to find all usages.
The problem is that such usage makes it impossible to use even on simple lambda:
session.Query<Foo>().Select(f=>f.SomeData)
throws error, as uppercase "SomeData" is not mapped, and
session.Query<Foo>().Select(f=>f.someData)
does not compile, as lowercase "someData" is protected.
What happens, if I will map BOTH field and property:
<property name="someData" access="field" column="SOME_DATA" />
<property name="SomeData" access="property" column="SOME_DATA" />
I tried quickly, and it seems to work, but will it have any drawback?
Is there any other simple solution, that will not require editing every criteria-based query in project?
Thanks for any help.
You can map the same column multiple times but with recent NHibernate versions only one of the properties need to be mapped as modifiable. So just add insert="false" update="false" to your additional mappings to avoid any issues in future:
<property name="someData" access="field" column="SOME_DATA" />
<property name="SomeData" access="property" column="SOME_DATA" update="false" insert="false" />
I need to retrieve all the users with a valid Wish property (so not null). This is the xml of my class:
<class name="Project.Engine.Domain.User,Project.Engine" table="Users" lazy="true">
<id name="UserID" column="UserID">
<generator class="native" />
</id>
<property name="Firstname" column="Firstname" type="string" not-null="true"
length="255" />
<property name="Lastname" column="Lastname" type="string" not-null="true"
length="255" />
<property name="Email" column="Email" type="string" not-null="true"
length="255" />
<one-to-one name="Wish" cascade="all" property-ref="UserID"
class="Project.Engine.Domain.Wish, Project.Engine" />
</class>
The method to get all my users is the following:
public PagedList<User> GetAll(int pageIndex, int pageSize,
string orderBy, string orderByAscOrDesc)
{
using (ISession session = NHibernateHelper.OpenSession())
{
var users = session.CreateCriteria(typeof(User));
users.Add(Restrictions.IsNotNull("Wish"));
return users.PagedList<User>(session, pageIndex, pageSize);
}
}
As you can notice, I have added the Restriction on the child object. This doesn't work properly as the method return all users including the ones with Wish property as null. Any help?
this is the xml for child:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Project.Engine.Domain.Wish,Project.Engine" table="Wish" lazy="false">
<id name="WishID" column="WishID">
<generator class="native" />
</id>
<property name="UserID" column="UserID" type="int" not-null="true" length="32" />
<property name="ContentText" column="ContentText" type="string" not-null="false" length="500" />
<property name="Views" column="Views" type="int" not-null="true" length="32" />
<property name="DateEntry" column="DateEntry" type="datetime" not-null="true" />
</class>
</hibernate-mapping>
Well, there is a bug with one-to-one and null testing of the side which may not exist. I had already encountered it but forgot about it. The property-ref just render it a bit more tricky to diagnose, but it does exist on actual one-to-one too.
Here is its corresponding issue in NHibernate tracking tool.
Workaround: test for null state of an non-nullable property of Wish, like Wish.Views.
Forgive the wild guess on test syntax, I do not use nhibernate-criteria anymore since years, but try by example:
public PagedList<User> GetAll(int pageIndex, int pageSize,
string orderBy, string orderByAscOrDesc)
{
using (ISession session = NHibernateHelper.OpenSession())
{
var users = session.CreateCriteria(typeof(User));
users.Add(Restrictions.IsNotNull("Wish.Views"));
return users.PagedList<User>(session, pageIndex, pageSize);
}
}
Using linq-to-nhibernate, I confirm this workaround works with my own projects, which gives by example:
// The "TotalAmount != null" seems to never be able to come false from a
// .Net run-time view, but converted to SQL, yes it can, if TransactionRecord
// does not exist.
// Beware, we may try "o.TransactionsRecord != null", but you would get struck
// by https://nhibernate.jira.com/browse/NH-3117 bug.
return q.Where(o => o.TransactionsRecord.TotalAmount != null);
I maintain my other answer since you may consider using a many-to-one instead, especially since you do not have made a bidirectionnal mapping (no corresponding constrained one-to-one in Wish) in addition to not having an actual one-to-one. many-to-one does not suffer of the bug.
one-to-one mapping using property-ref is not an "actual" one-to-one, and usually this is a sign a many-to-one mapping should be used instead.
Maybe this is not related to your trouble, but you may give it a try.
An "actual" one-to-one has the dependent table primary key equals to the parent table primary key. (Dependent table, Wish in your case, would have a foreign primary key, UserId in your case. See this example.)
I have sometime "played" with 'one-to-one property-ref', and I always ended giving it up due to many issues. I replaced that with more classical mappings, either changing my db for having an actual one-to-one, or using a many-to-one and living with a collection on child side though it would always contain a single element.
I have a problem when using Hibernate Criteria API:
var query = session.QueryOver<MyClass>().Where(param => param.Name == "myFilterName").List<MyClass>();
If a run this statement, a NHibernate.QueryException is thrown:
could not resolve property: Name of: MyClass
And in the StackTrace:
at NHibernate.Persister.Entity.AbstractPropertyMapping.ToType(String
propertyName)
MyClass.hbm.xml file has the property mapped of this way:
<property name="name" access="field">
<column name="NAME" length="50" not-null="true" />
</property>
I think that the problem comes because hibernate can not access the property "Name" of MyClass because is mapped with access="field", but I can not change this way to access the property due application design requirements.
The idea is create querys by using Criteria API with lambda expressions in order to avoid hardcoded string property names.
Also I´ve tried with a Expression with the same exception result:
var criterion = Expression.Where<MyClass>(param => param.Name == "myFilterName");
var result = session.CreateCriteria<MyClass>().Add(criterion).List<MyClass>();
Somebody knows how I can indicate to Criteria API that MyClass has the properties mapped as access="field"?
Help very appreciated.
Not sure of what you want to achieve, having the class code might help.
Anyway, from what you provided, I guess the mapping should be :
<property name="Name" access="field.camelcase">
see http://www.nhforge.org/doc/nh/en/#mapping-declaration-property
I have a class StoreHours that has a composite key and has been working perfectly. A new demand came up for another type of hours to be returned. I thought "simple, I'll abstract the base class, have two concrete implementations and change my references in the app to one of the new classes". However, upon doing that, my unit tests failed with
X.Test.StoreTest.HoursTest: NHibernate.InstantiationException : Cannot instantiate abstract class or interface: X.Model.StoreHours
My mapping file looks like
<class name="StoreHours" table="StoreHour" abstract="true" discriminator-value="0" >
<composite-id>
<key-many-to-one name="Store"
class="Store"
column="StoreUid"/>
<key-property name="DayOfWeek"
column="DayOfWeekId"
type="System.DayOfWeek" />
</composite-id>
<discriminator column="StoreHourType" type="Byte" />
<property name="OpenMinutes" column="OpenTime" />
<property name="CloseMinutes" column="CloseTime" />
<subclass name="OfficeHours" discriminator-value="1" />
<subclass name="AccessHours" discriminator-value="2" />
</class>
I found someone with similar troubles here and started down their solution path but actually ended up with even more troubles than I started with.
I can persist the records to the database perfectly but onload, NHibernate is trying to instantiate the abstract 'StoreHours' even though I've only got a strongly type set off 'OfficeHours'
This seems like a really trivial requirement so I figure I must be doing something simple wrong. All hints appreciated.
The problem is in the way you are using the composite-id
Table-per-class works with Composite-id, but only if the composite is
implemented as a class
so you need to create a class like
public class StoreHoursCompositeId
{
public virtual Store Store { get; set; }
public virtual DayOfWeek DayOfWeek { get; set; }
// Implement GetHashCode(), is NH-mandatory
// Implement Equals(object obj), is NH-mandatory
}
In your StoreHours object create a property which use the above class (in my example I called it "StoreHoursCompositeId")
Your mapping become:
<class name="StoreHours" table="StoreHour" abstract="true" discriminator-value="0" >
<composite-id name="StoreHoursCompositeId" class="StoreHoursCompositeId">
<key-many-to-one name="Store" class="Store"
column="StoreUid"/>
<key-property name="DayOfWeek"
column="DayOfWeekId"
type="System.DayOfWeek" />
</composite-id>
<discriminator column="StoreHourType" type="Byte" />
<property name="OpenMinutes" column="OpenTime" />
<property name="CloseMinutes" column="CloseTime" />
<subclass name="OfficeHours" discriminator-value="1" />
<subclass name="AccessHours" discriminator-value="2" />
</class>
I had the very same problem and this fixed it for me.
I started using NHibernate this week (struggling). I have a small application with 3 tables (I use 2 for now). Table currency and table country here are the mapping files.
<class name="dataprovider.Country,dataprovider" table="country">
<id name="CountryId" column="country_id" unsaved-value="0">
<generator class="native"/>
</id>
<!--<bag name="BatchList" inverse="true" lazy="true" >
<key column="country_id" />
<one-to-many class="Batch" />
</bag>
<bag name="PrinterList" inverse="true" lazy="true" >
<key column="country_id" />
<one-to-many class="Printer" />
</bag>-->
<many-to-one name="CurrencyId" column="currency_id" class="Currency" cascade="save-update"/>
<!--<property column="currency_id" name="Currency_Id"/>-->
<property column="name" name="Name"/>
<property column="region" name="Region" />
<property column="comments" name="Comments"/>
</class>
The currency mapping file:
<class name="dataprovider.Currency, dataprovider" table="currency">
<id name="CurrencyId" column="currency_id" >
<generator class="native"/>
</id>
<bag name="CountryList" inverse="true" lazy="true" >
<key column="currency_id" />
<one-to-many class="Country" />
</bag>
<!--<bag name="DenominationList" inverse="true" lazy="true" >
<key column="currency_id" />
<one-to-many class="Denomination" />
</bag>-->
<property column="name" name="Name"/>
<property column="authorizer" name="Authorizer" />
<property column="date_created" name="DateCreated" type="DateTime" not-null="true" />
<property column="comments" name="Comments" />
The many to one relationship that country hold create an attribute of the type Currency in the country persistence class. Now while my test can_add_currency and can_add_country succeeded (I export the schema) I have null value in the table country on the field currency_id.
Here is the test code:
[Test]
public void can_add_new_country()
{
CountryManager cm = new CountryManager();
Country country = new Country();
//country.CurrencyId = CurrencyManager.GetCurrencyById(1);
country.CurrencyId = new CurrencyManager().GetCurrencyById(1);
country.Name = "POUND";
country.Region = "ENGLAND";
country.Comments = "the comment";
cm.Add(country);
using(ISession session = _sessionFactory.OpenSession())
{
Country fromdb = session.Get<Country>(country.CountryId);
Assert.IsNotNull(fromdb);
Assert.AreNotSame(fromdb, country);
}
}
public Currency GetCurrencyById(int currency_id)
{//GetCurrencyById from CurrencyManger class
try
{
using(ISession session = NHibernateHelper.OpenSession())
{
return session.Get<Currency>(currency_id);
}
} catch (Exception ex)
{
return null;
}
}
The question is: how to insert into table country with the currency_id of an existing currency_id from the table currency?
How do you guys/gals do it? I'm seriously stuck and a 2 day small project is taking me one week now.
Set cascade="save-update" on your bag name="CountryList". If that doesn't work, it may be helpful to post your code for CountryManager.Add() to see how the saving is taking place.
In response to your second question, if I understand it correctly, this is how NHibernate treats mapped collections:
You mapped the collection as lazy, so loading the object will not load all the elements of the collection at the same time. Instead, when you first access the collection NHibernate will query the database to fill the collection and return it. So, when you first do something like:
var countries = currency.CountryList;
or
foreach (Country country in currency.CountryList)
NHibernate will silently execute a query similar to:
SELECT * FROM country WHERE currency_id = ?
And then build a collection of Country objects to return (and cache so that the query is not run again).
Basically, through the mapping file you've already told NHibernate all about your two entities (Country and Currency) and how they are related so it knows how to build the queries to access the data. Similarly, it keeps track of what was in the collection so when you add or remove items, it can compare what was changed and execute the appropriate INSERT or REMOVE statements.
So, the way to use collections mapped by NHibernate is to use them just as you would with a normal .NET collection. Add and remove items at your will. Just when you are finished, make sure you tell NHibernate to persist the changes you made to the database, either by calling session.Save() or session.Delete() on every item you add/remove or (if you have set cascading, like you have) simple call session.Save() on the parent object that contains the collection.
My cascade was rather on the this side:
<many-to-one name="CurrencyId" column="currency_id" class="Currency" cascade="save-update"/>
After I changed it it wasn't working at first even though I rebuild the solution. Then I did another test from the Currency_Test class: can_get_currency_by_id which call the same function GetCurrncyById and I could have an object while from can_add_new_country the same function returns null.
Then I realise that the ExportSchema of either Country_Test [Setup] or Currency_Test is not creating the database on time for the can_add_new_product to have a currency object. That's why it's returning null object.
Now not to abuse; but can you tell me how to use IList<Counrty>CountryList? I don't know if I put it well. From my understanding it should store all country objects using the same currency (currency_id reference). How does NHibernate do that?