NHibernate Get&字串编号 [英] NHibernate Get & string Id

查看:83
本文介绍了NHibernate Get&字串编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在NHibernate上分配了字符串Id的实体,当我通过ID获取实体时遇到了一个小问题.

I've an entity with assigned string Id on NHibernate and I've a little problem when get an entity by Id.

示例...

假设有这样的数据库记录...

Suppose that have a database record like this...

Id    Description
-------------------
AAA   MyDescription

现在,如果我使用搜索ID为"aaa"的获取"方法...

now, if I use "Get" method using search id "aaa"...

MYENTITYTYPE entity = Session.Get<MYENTITYTYPE>("aaa")

返回权实体,但ID字段(entity.Id)为"aaa",但我希望它等于"AAA".

return right entity but Id field (entity.Id) is "aaa", while I wish it were equal to "AAA".

总而言之,我希望"Get"方法返回与数据库中存储的ID相同的ID ...大小写相同.

In summary I would like that "Get" method return the id identical to the one stored in the database...with the same case.

可能吗?我该怎么办?

推荐答案

有趣的问题.我的猜测是不可能,因为该ID可能在数据库调用之前之前存在.请考虑以下内容:

Interesting question. My guess is that it's not possible, because the Id might exist before the DB call. Consider the following:

var foo = session.Load<Foo>("aaa"); //no DB call, foo is a proxy
Console.WriteLine(foo.Id); //Prints "aaa";
var bar = foo.Bar; //Forces loading
Console.WriteLine(foo.Id); //No matter what, the Id can't change at this point

这说明了具有含义的主键通常是个坏主意的另一个原因,尤其是在其输入不受控制的情况下.

This illustrates another reason why primary keys with meaning are usually a bad idea, especially if their input is not controlled.

现在,如果您使用查询而不是Get,则会获得右写的ID:

Now, if instead of Get you use a query, you will get the right-cased Id:

//example with LINQ; you can use HQL, Criteria, etc
var foo = session.Query<Foo>().Single(x => x.Id == "aaa");

缺点是,即使实体已经加载,您也将始终访问数据库.

The drawback is that you will always go to the DB, even if the entity is already loaded.

现在,如果您将实体定义为 {Id,代码,描述} ,其中Id是合成POID(我建议 Hilo Guid ),而Code是现有的字符串ID,则可以避免由于使用Get而不是使用代码查询而引起的潜在错误.

Now, if you defined your entity as {Id, Code, Description}, where Id is a synthetic POID (I recommend Hilo or Guid) and Code is the existing string Id, you will avoid potential bugs caused by using Get instead of a query with the code.

这篇关于NHibernate Get&amp;字串编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆