映射“值对象” (流畅)NHibernate 中的集合
我有以下实体
public class Employee
{
public virtual int Id {get;set;}
public virtual ISet<Hour> XboxBreakHours{get;set}
public virtual ISet<Hour> CoffeeBreakHours {get;set}
}
public class Hour
{
public DateTime Time {get;set;}
}
(我在这里要做的是存储员工 A 每天 9:00 13:30 玩 Xbox 的信息,每天 7:00 12:30 18:00 喝咖啡休息) - 我是不确定我的方法在这里是否有效。
问题是我的(理想情况下流畅的)映射应该是什么样子? (从我的角度来看)Hour 类没有必要有 Id 或可以从某种存储库访问。
I have the following entity
public class Employee
{
public virtual int Id {get;set;}
public virtual ISet<Hour> XboxBreakHours{get;set}
public virtual ISet<Hour> CoffeeBreakHours {get;set}
}
public class Hour
{
public DateTime Time {get;set;}
}
(What I want to do here is store information that employee A plays Xbox everyday let's say at 9:00 13:30 and has a coffee break everyday at 7:00 12:30 18:00) - I am not sure if my approach is valid at all here.
The question is how should my (ideally fluent) mappings look like here? It is not necessary (from my point of view) for Hour class to have Id or be accessible from some kind of repository.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您想要的方式,您需要将集合映射为元素映射或组件集合(即NHibernate 术语)。前者需要一个
和IUserType
定义,而后者则适用于您想让Hour
类拥有多个属性的情况。如果您坚持使用单个属性,则需要定义一个
IUserType
,以便 NHibernate 知道如何在您的类型与数据库之间进行转换。完成此操作后,您可以使用 Fluent NHibernate 映射它,如下所示:这指定您的集合存储在一个表中,该表的一个名为
value
的列包含实际值。CustomType
调用告诉 NHibernate 使用IUserType
来处理这个集合。如果您要在
Hour
类中拥有多个属性,那么您需要执行以下操作(注意:这实际上与执行Component
映射非常相似)。Depending on how you want to do it, you either need to map your collection as an element mapping or as a component collection (that's
<element>
and<composite-element>
in NHibernate terms). The former will need anIUserType
defining, while the latter is for if you're going to have yourHour
class have more than one property.If you're sticking with a single property, you'll need to define an
IUserType
so NHibernate knows how to translate to and from your type to your database. Once you've done that, you can map it with Fluent NHibernate like so:That specifies that your collection is stored in a table with a column called
value
containing the actual values. TheCustomType
call is what tells NHibernate to use theIUserType
for this collection.If you're going to have multiple properties in your
Hour
class, then you need to do the following (note: this is actually very similar to doing aComponent
mapping).