开发者

NHibernate.TypeMismatchException: Provided id of the wrong type. Expected: System.Int32, got System.Int64

Am using the following query to get a Client. The Client has a public Id of type long.

var client = Session.CreateQuery("from Client as c where c.Id = :Id").SetParameter("Id", 1, NHibernateUtil.Int64).UniqueResult<Client>();

Am getting the error:

NHibernate.TypeMismatchException: Provided id of the wrong type. Expected: System.Int32, got System.Int64

At the same time, the following works just fine.

var client = Session.Get<Client>(1L); //Or
var client = Session.CreateCriteria<Client>().Add(Restrictions.Eq("Id", 1L)).UniqueResult<Client>();

What am i missing? Am using fluent nhibernate to开发者_JAVA百科 create the mappings. I have tested the queries against a Sqlite and a MySql database. Same results.

Edit1: The schema generation from the mappings clearly is using bigint for the primary key on mysql. Thats why i am unable to understand what is expecting a Int32?

Edit2: okay, my Client class has a reference to a Report object. Its actually a one-to-one relationship in the db with the report table having a column clientID. The Report class had an id of type int. Once i changed its type to long, the error went away.

My mappings are as follows:

ClientMap:

HasOne<Report>(x => x.Report)
   .PropertyRef(x => x.Client)
   .LazyLoad()
   .Cascade.SaveUpdate();

ReportMap:

References(x => x.Client, "clientID").Unique();

So, why did the problem solve itself by changing the type of the reportid from int to long. Secondly, why is it even bothering to fetch the report when i am not asking for it?


One-to-one keys need to have the same type definition since they use the same values. So a Client with ID = Int32.MaxValue + 1 would have a corresponding Report with ID = Int32.MaxValue + 1 so they have to be both long.

I recommend these articles to understand one-to-one and how most of the time you don't really need it:

  • http://blog.jagregory.com/2009/01/27/i-think-you-mean-a-many-to-one-sir/
  • http://web.archive.org/web/20100331014510/http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/11/18/legacy-db-and-one-to-one-relations.aspx?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜