【发布时间】:2015-11-12 16:47:32
【问题描述】:
请有人解释一下复合 ID 在 NHibernate 中是如何工作的?
我想我错过了什么。这就是我正在做的。
我有一个名为 TeamMemberUnified 的 TeamMember 类,因为我试图将两个不同的数据库与视图链接起来以创建一个统一的数据库。每个 TeamMember 实例都与一个人在建筑物中所扮演的角色相关。
public class TeamMemberUnified: DataItem
{
public virtual int Id { get; set; }
// person / contact details
public virtual byte[] ContactId { get; set; }
public virtual Contact Contact { get; set; }
/// property id
public virtual string PropIdUnified { get; set; }
public virtual string UnifiedDbCode { get; set; }
public virtual int RoleId { get; set; }
// role the person plays at this property
public virtual TeamRoleUnified TeamRole { get; set; }
}
一个人在建筑物中扮演的角色由 TeamRole 类表示。几乎是静态数据/查找类
public class TeamRoleUnified: DataItem
{
public virtual int RoleId { get; set; }
public virtual string Title{ get; set; }
public virtual string UnifiedDbCode { get; set; }
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
var that = (TeamRoleUnified)obj;
return this.RoleId == that.RoleId &&
this.UnifiedDbCode == that.UnifiedDbCode;
}
public override int GetHashCode()
{
return RoleId.GetHashCode() ^
UnifiedDbCode.GetHashCode();
}
}
这是团队成员的地图
public class TeamMemberUnifiedMap : ClassMap<TeamMemberUnified>
{
public TeamMemberUnifiedMap()
{
Id(x => x.Id, "Id");
Map(x => x.ContactId);
Map(x => x.PropIdUnified);
Map(x => x.UnifiedDbCode);
// team member has one role at this building
References(t => t.TeamRole)
.Columns(new string[] {"RoleId", "UnifiedDbCode"});
Table("dbo.TeamMembers");
}
}
虽然 TeamRole 与此类映射。 RoleId 是一个唯一的 Id,但现在我已经在一个视图中“合并”了两个数据库中的两个数据库/引用的表,RoleId 仅在每个 Db 的行中是唯一的。 Db 由 UnifiedDbCode 限定。
public class TeamRoleUnifiedMap : ClassMap<TeamRoleUnified>
{
public TeamRoleUnifiedMap()
{
CompositeId()
.KeyProperty(x => x.RoleId)
.KeyProperty(x => x.UnifiedDbCode);
//References(x => x.)
Map(x => x.RoleId);
Map(x => x.Title);
Map(x => x.UnifiedDbCode);
Table("dbo.TeamRoles");
}
}
我的理解是我需要在 TeamRole 上定义一个复合 Id 来定义如何唯一标识行。
但是,当我尝试运行代码时,出现此错误:
{"外键 (FK8FB93FCE3B0D5D3E:dbo.TeamMembers [RoleId])) 必须与引用的主键具有相同的列数 (dbo.TeamRoles [RoleId, UnifiedDbCode])"}
【问题讨论】:
标签: c# sql-server nhibernate fluent