[英]NHibernate Mapping a Table Were the Primary Key is Also a Foreign Key
I have 2 tables as follows: 我有2个表如下:
create table Users
(
UserId int primary key identity not null
)
create table UserExternalKeys
(
UserIdRef int primary key not null,
ExternalKey varchar(50) unique not null
)
alter table UserExternalKeys
add constraint fk_UsersExternalKeys_Users
foreign key (UserIdRef)
references Users (UserId)
Each user can have a 0 or 1 external keys. 每个用户可以拥有0或1个外部密钥。 Things are setup this way because adding a nullable unique column to SQL Server does not allow for more than 1 null value. 事情是通过这种方式设置的,因为向SQL Server添加可为空的唯一列不允许多于1个空值。
Based on Ayende's post , it seems like this could be handled using a <one-to-one>
mapping. 根据Ayende的帖子 ,似乎可以使用<one-to-one>
映射来处理。 However, this would require the UserExternalKeys
table to have its own primary key. 但是,这将要求UserExternalKeys
表具有其自己的主键。
The new schema would look something like this: 新架构看起来像这样:
create table Users
(
UserId int primary key identity not null,
ExternalKeyRef int null
)
create table UserExternalKeys
(
UserExternalKeyId int primary key identity not null,
ExternalKey varchar(50) unique not null
)
alter table Users
add constraint fk_Users_UsersExternalKeys
foreign key (ExternalKeyRef)
references UserExternalKeys (UserExternalKeyId)
I think this would work, but it feels like I would only be adding the UserExternalKeyId
column to appease NHibernate. 我认为这样可行,但感觉我只会添加UserExternalKeyId
列来安抚NHibernate。
Any suggestions? 有什么建议么?
If a user can have 0 or 1 external keys why not design the tables as: 如果用户可以拥有0或1个外部密钥,为什么不将表设计为:
create table Users
(
UserId int primary key identity not null
ExternalKey varchar(50) null
)
and use one of the known workarounds for this problem. 并使用已知的解决方法之一来解决此问题。 If you're using SQL Server 2008 you can use a filtered index . 如果您使用的是SQL Server 2008,则可以使用过滤索引 。 If you're using an earlier version you can use a trigger, an indexed view (2005), or the nullbuster workaround . 如果您使用的是早期版本,则可以使用触发器,索引视图(2005)或nullbuster解决方法 。
You could also keep your original schema and map the relationship as one-to-many from Users to UserExternalKeys. 您还可以保留原始架构,并将关系从“用户”一对多映射到UserExternalKeys。 Map the collection as a private member and expose access to it through a property: 将集合映射为私有成员,并通过属性公开对它的访问:
private IList<UserExternalKeys> _externalKeys;
public string ExternalKeys
{
get
{
if (_externalKeys.Count() == 1)
{
return _externalKeys.ElementAt(0).ExternalKey;
}
else
{
// return null or empty string if count = 0, throw exception if > 1
}
}
set
{
if (_externalKeys.Count() == 0) { // add key and set value }
else { // set value if count = 1, throw exception if > 1 }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.