[英]one to one mapping in nhibernate
我正在使用nhibernate。 我的代码如下
public class Store
{
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
public virtual IList<Employee> Staff { get; set; }
public Store()
{
Staff = new List<Employee>();
}
}
员工阶层
public class Employee
{
public virtual int Id { get; protected set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual Store Store { get; set; }
}
storemap
public class StoreMap:ClassMap<Store>
{
public StoreMap()
{
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.Staff).WithKeyColumn("store");
}
}
EmployeeMap的
public EmployeeMap ()
{
Id(x => x.Id);
Map(x => x.FirstName);
Map(x => x.LastName);
References(x => x.Store ).WithColumns("store");
}
这很好。 但是我想在员工和商店之间建立一对一的关系,为此,我尝试这样做,但这种方法不起作用。 在employeemap引用中(x => x.Store).WithForeignKey(“ store”); 并在暴风雨中
HasOne(x => x.Staff).WithForeignKey("store");
但这导致以下错误
持久类未知:
System.Collections.Generic.IList`1[[test.Models.Employee, test,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
请帮忙
one-to-one
映射非常具体。 它说,一个对象不能存在而另一个则不能存在。 检查文档5.1.11。 一对一 ,这对于流利而言如何使流利的休眠一对一映射? 。
我们可以举个例子:
public StoreMap()
{
Id(x => x.Id);
HasOne(x => x.Staff).Cascade.All();
}
public EmployeeMap()
{
Id(x => x.Id).GeneratedBy.Foreign("Store");
HasOne(x => x.Store).Constrained();
}
问题出在哪儿? 现在我们有了可以单独居住的Store
。 没关系。 但是任何Employee
都将需要分配Store
。 还有更重要的是... Employee
将没有自己的ID列。 实际上它将是可以命名为“ StoreId”的列,因为ID值将来自Store.ID
这种情况非常罕见。 实际上,在我看来,您已经拥有的映射非常好。
我猜您正在尝试限制分配给该Store
的Staff
数量。 这可能是合理的,我们可以在Buisness层上实现这一目标。
一个清晰(简化)的示例可能是这样的:
public class Store
{
...
// not public
protected virtual IList<Employee> Staff { get; set; }
// here we do the trick on top of the mapping/hidden persistence layer
public virtual Employee Employee
{
get { return Staff.FirstOrDefault(); }
set { Staff[0] = value ; }
列表virtual IList<Employee> Staff
无法映射到HasOne
只需使其不成为列表即可;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.