我有以下C#类(简化):
class Entity {
Guid Id { get; set;}
ISet<Uri> Urls { get; set; }
}
我想将它映射到下面的表结构:
TABLE Entity (
Id uniqueidentifier PRIMARY KEY
)
TABLE EntityUrls (
Id uniqueidentifier PRIMARY KEY,
EntityId uniqueidentifier FOREIGN KEY REFERENCES(Entity.Id),
Uri varchar(250)
)
我几乎可以使用<set>
来映射它
<set name="Urls" table="EntityUrls">
<key column="EntityId"/>
<element column="Uri" type="..."/>
</set>
但是如何映射EntityUrls.Id
列(至少在INSERT
上生成Guid)?
或者通常建议在这种情况下使用复合PK?
答案 0 :(得分:1)
您可以尝试创建实现ICompositeUserType
的自定义用户类型:
<set name="Urls" table="EntityUrls">
<key column="EntityId"/>
<element type="UserTypes.UriCompositeUserType">
<column name="Id" />
<column name="Uri" />
</element>
</set>
以下是NHibernate对ICompositeUserType
所说的内容:
A UserType that may be dereferenced in a query. This interface allows a custom type to define "properties". These need not necessarily correspond to physical .NET style properties. A ICompositeUserType may be used in almost every way that a component may be used. It may even contain many-to-one associations. Implementors must be immutable and must declare a public default constructor. Unlike UserType, cacheability does not depend upon serializability. Instead, Assemble() and Disassemble() provide conversion to/from a cacheable representation.