将外键映射到主键以外的其他键

时间:2012-11-16 10:56:12

标签: .net nhibernate fluent-nhibernate

在我的数据库中有表分配工作区,从概念上讲,每项任务都只在一个工作场所进行。 分配表包含一列 Workplace ,它是引用 Workplace 表的 WorkplaceName 列的外键。

这是架构:

table Workplace (
  ID int primary key,
  WorkplaceName int
)

table Assignment (
  Workplace int
)

我的映射:

class Workplace
{
  public virtual int ID { get; set; }
  public virtual int WorkplaceName { get; set; }
} 

class Assignment 
{
  public virtual Workplace { get; set; }
}

class AssignmentMap : ClassMap<Assignment>
{
  public AssignmentMap()
  {
    References(a => a.Workplace);
  }
}

在运行时我得到异常

  

不存在具有给定标识符的行[MyProject.Workplace#2001]

这里的问题似乎是FH在 Workplace.ID 列中查找 Assignment.Workplace 属性的值,即表的主键;正确的位置是 Workplace.WorkplaceName 列。我尝试使用ForeignName方法,认为我可以通过这种方式指定 WorkplaceName 。如何告诉FH如何加入正确的列?

2 个答案:

答案 0 :(得分:2)

我在这里找到了答案:FluentNHibernate Many-To-One References where Foreign Key is not to Primary Key and column names are different

解决方案是使用PropertyRef;该行现在读取:

References(x => x.Workplace).PropertyRef(x => x.WorkplaceName).Fetch.Join();

我没有意识到我需要提供对客户端对象的属性 WorkplaceName 的引用,而不是尝试指示映射使用服务器端列 WorkplaceName

答案 1 :(得分:0)

我认为它必须像

References(x => x.Workplace).Column("WorkplaceName")

相关问题