从查找表返回描述的流畅NHibernate映射



我们有以下数据库结构:

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(即使用带有覆盖的自动映射类)。

我们正试图从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"实体,因为我们真正关心的是描述值——这是用户可配置的,所以我们也不能只使用enum。有人能帮忙吗?

Join使用父表的主键。不可能将其更改为外键。有关Join的更多细节,请参阅文档。

在这种情况下,我建议为查找创建一个实体。但是如果你真的想采用这种方法,你可以用一个公式来映射属性,例如
Map(x => x.Role).Formula("(select description from libRole where Id = RoleId)");

注意,这不是完美的,因为它使用RoleId,所以如果查询有另一个表的列名为RoleId,那么DBMS在尝试执行SQL时会报错。

最新更新