NHibernate的处理字符串的主键和关系字符串、主键、关系、NHibernate

2023-09-04 02:44:26 作者:展眉

我刚刚被难住了这个问题了一个小时,我发现烦人的问题也说不定。

I've have just been stumped with this problem for an hour and I annoyingly found the problem eventually.

情况

我有哪些用户的字符串作为主键,这个表有多种多对一和多对多关系的表全部关闭此主键。

I have a table which users a string as a primary key, this table has various many to one and many to many relationships all off this primary key.

当查找表中的所有关系都带回多个项目。然而,每当我试图让通过主键(串)的对象时,它并没有带回任何关系,他们总是设置为0。

When searching for multiple items from the table all relationships were brought back. However whenever I tried to get the object by the primary key (string) it was not bringing back any relationships, they were always set to 0.

部分解

所以,我看着我的日志,看看有什么SQL在做什么,这是返回正确的结果。于是,我尝试过各种事情在各种随机的方式,并最终制定出它是。字符串的情况下被传递到get方法是不完全一样的情况下,因为它是在数据库中,所以当它试图关系项目匹配了它什么也没找到的主要实体(或者至少NHibernate的是不是因为正如我所说的上述SQL实际上返回正确的结果)

So I looked into my logs to see what the SQL was doing and that was returning the correct results. So I tried various things in all sorts of random ways and eventually worked out it was. The case of the string being passed into the get method was not EXACTLY the same case as it was in the database, so when it tried to match up the relationship items with the main entity it was finding nothing (Or at least NHIbernate wasn't because as I stated above the SQL was actually returning the correct results)

真正的解决办法

有没有其他人遇到过吗?如果是这样,你如何告诉NHibernate的SQL结果匹配到实体时忽略大小写?这是愚蠢的,因为它的工作非常清楚之前,突然它已经开始关注到字符串的情况下,现在所有的。

Has anyone else come across this? If so how do you tell NHibernate to ignore case when matching SQL results to the entity? It is silly because it worked perfectly well before now all of a sudden it has started to pay attention to the case of the string.

推荐答案

我在我的数据库上裁判台完全相同的情况。我映射架构文件​​,你也做了同样的方式。在code,当我查询按主键的记录,我在使用的NHibernate的ISession的实例如下:

I have the exact same situation on a ref table in my DB. I mapped the schema file the same way you did. In code, when I query for the record by Primary Key, I do the following using an instance of the NHibernate ISession:

return session.Get<T>(id);

在此声明中,T是您要查询的类型,id是字符串ID,你正在寻找(主键)

In this statement, T is the type you are querying for, and id is the string id you are looking for (the Primary Key)

下面是我的映射文件的例子:

Here is an example of my mapping file:

    <class name="Merchant" table="T__MERCHANT">
        <id name="MerchantId" column="MERCHANT_ID" type="string">
            <generator class="assigned" />
        </id>

        <property name="MerchantStatusId" column="MERCHANT_STATUS_ID" type="Char" not-null="true" length="1" />
        <property name="MerchantStatusName" column="MERCHANT_STATUS_NAME" type="string" length="50" />
        <property name="MerchantName" column="NAME" type="string" not-null="true" length="50" />
 </class>
</hibernate-mapping>

和我的C#code是这样的:

And my C# code looks like this:

public Merchant GetMerchantById(string id)
{
     return session.Get<Merchant>(id);
}