NHibernate的:加入表,并从其他表中单列 [英] Nhibernate: join tables and get single column from other table
问题描述
我有以下表格:
create table Users(
Id uniqueidentifier primary key,
InfoId uniqueidentifier not null unique,
Password nvarchar(255) not null
)
Create table UserInfo(
Id uniqueidentifier primary key,
Company nvarchar(255) not null,
ContactPerson nvarchar(255) not null
)
和 InfoId
是一个外键引用的UserInfo(ID)
。
我想这个映射到以下类:
I want to map this to the following class:
public class UserCredentials
{
public virtual Guid Id { get; set; }
public virtual string UserName { get; set; }
public virtual string PasswordHash { get; set; }
protected UserCredentials() { }
}
我想下面的映射:
I want to following mapping:
Id --> Users(Id)
UserName --> UserInfo(Company)
PasswordHash --> Users(Password)
我尝试了以下映射:
I tried the following mapping:
<hibernate-mapping xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:nhibernate-mapping-2.2">
<class name="UserCredentials" table="Users">
<id name="Id" type="Guid">
<generator class="guid.comb" />
</id>
<property name="PasswordHash" not-null="true" column="Password"/>
<join table="UserInfo">
<key column="Id" foreign-key="InfoId"/>
<property name="UserName" column="Company" not-null="true" />
</join>
</class>
</hibernate-mapping>
但似乎&LT;键&GT;
元素被错误地指定(即外键
属性)不做我想做的。如果我离开了外键
属性,它试图加入两个表的编号
列,这是不正确的。
But it seems the <key>
element is incorrectly specified (the foreign-key
attribute) does not do what I want. If I leave out the foreign-key
attribute, it tries to join on the Id
columns of both tables, which is not correct.
我不希望包括我的 UserCredentials
类的<code> InfoId 属性,如果有可能避免
I don't want to include an InfoId
property on my UserCredentials
class if it is possible to avoid it.
谁能帮我达到预期的映射?
Can anyone help me achieve the desired mapping?
推荐答案
当你想加入的realation或只是一个表像你这样在这里的基础上而不是主键,但在一些列需要使用属性-ref属性。
When you want to join in a realation or just another table like you do here based on not the primary key but on some other column you need to use the property-ref attribute.
是这样的:
like this:
<property name="InfoId" not-null="true" column="InfoId"/>
<property name="PasswordHash" not-null="true" column="Password"/>
<join table="UserInfo">
<key column="Id" property-ref="InfoId"/>
<property name="UserName" column="Company" not-null="true" />
</join>
这意味着你还需要添加InfoId你UserCredentials类,目前还没有办法MAPP关系或加入像上面使用,你必须speficy一个属性的列名(NH将使用列属性指)
This means that you need to also add InfoId to your UserCredentials class, there is currently no way to mapp a relation or a join like above by using a column name you have to speficy a property (NH will use the column that property refers to)
在一个侧面说明,外键属性有一点missleading,它只是规定,如果你让NHibernate的创建数据库模式将要生成的数据库外键的名称。
On a side note, the foreign-key attribute is a little missleading, it only specifies the name of the database foreign key that will be generated if you let nhibernate create the database schema.
这篇关于NHibernate的:加入表,并从其他表中单列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!