C# nhibernate中的一对一映射
我用的是nhibernate。我的代码如下C# nhibernate中的一对一映射,c#,nhibernate,mapping,C#,Nhibernate,Mapping,我用的是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() {
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 StoreMap:ClassMap<Store>
{
public StoreMap()
{
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.Staff).WithKeyColumn("store");
}
}
这很好用。但我想在员工和商店之间建立一对一的关系,为此我尝试了这个方法,但没有效果。
在员工地图中
引用(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]]
请帮助列表虚拟IList员工
无法映射到HasOne
简单地让它不成为一个列表就可以了;) 一对一的映射非常具体。它说,一个物体不能没有另一个而存在。检查文档和此文件是否流畅 我们可以以liek为例:
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();
}
问题在哪里?现在我们有了商店
,它可以独自生活。没关系。但是任何员工
都需要分配一个商店
。更重要的是。。。员工
没有自己的ID列。它实际上是可以命名为“StoreId”的列,因为ID值来自Store.ID
建议
这种情况非常罕见。事实上,在我看来,你已经拥有的映射非常好
我猜您是在试图限制分配给商店的员工人数。这可能是合理的,我们可以在业务层实现这一点
一个清晰(简化)的例子可以是这样的:
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 ; }
公共类存储
{
...
//不公开
受保护的虚拟IList人员{get;set;}
//在这里,我们在映射/隐藏持久性层的顶部执行这个技巧
公共虚拟员工
{
获取{return Staff.FirstOrDefault();}
设置{Staff[0]=value;}
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();
}
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 ; }