Fluent NHibernate映射从查找表返回描述

时间:2013-04-15 11:16:04

标签: nhibernate fluent-nhibernate fluent-nhibernate-mapping

我们有以下数据库结构:

UserTeam table
Id (PK, int not null)
UserId (FK, int, not null)
TeamId (FK, int, not null)
RoleId (FK, int, not null)

libRole table
Id (PK, int not null)
Description (varchar(255), not null)

我们有一个实体如下:

public class UserTeam
{
    public int Id { get; set; }
    public Team Team { get; set; }
    public User User { get; set; }
    public int RoleId { get; set; }
    public string Role { get; set; }
}

我们正在使用Fluent NHibernate并自动配置NHibernate(即使用带覆盖的Automapping类)。

我们试图将libRole表中的描述列放到UserTeam表的“Role”属性中,但真的很难。以下是我们最接近的:

public class UserTeamMap : IAutoMappingOverride<UserTeam>
{
    public void Override( FluentNHibernate.Automapping.AutoMapping<UserTeam> mapping )
    {
        mapping.References( m => m.User ).Column( "UserId" );
        mapping.References( m => m.Team ).Column( "TeamId" );

        mapping.Join("Role", join =>
            {
                join.Fetch.Join();
                join.KeyColumn( "Id" );
                join.Map( x => x.Role, "Description" );
            } );
    }

}

生成以下SQL:

SELECT
    TOP (@p0)  this_.Id as Id70_0_,
    this_.RoleId as RoleId70_0_,
    this_.TeamId as TeamId70_0_,
    this_.UserId as UserId70_0_,
    this_1_.Description as Descript2_71_0_ 
FROM
    [UserTeam] this_ 
inner join
    libRole this_1_ 
        on this_.Id=this_1_.Id;

关闭,但是NHibernate在联接中的UserTeam表和libRole表上都使用了Id列,它应该在this_.RoleId=this_1_.Id上进行

我们缺少什么?我们真的不想在应用程序中创建一个“libRole”实体,因为我们真正关心的是描述值 - 用户可配置的,所以我们也不能只使用枚举。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

Join使用父表的主键。无法将其更改为外键。有关Join的可能性的详细信息,请参阅docs

在这种情况下,我建议为查找创建一个实体。但是如果你真的想采用这种方法,你可以用一个公式来映射属性,即

Map(x => x.Role).Formula("(select description from libRole where Id = RoleId)");

请注意,这并不完美,因为它使用RoleId,因此如果查询中有另一个包含RoleId列的表,那么DBMS会在尝试执行SQL时抱怨。