我有以下Nhiberhate流畅的映射,但我无法弄清楚如何在其中一个连接中获取where子句。我只想加入OperationKind ==“TASK”的操作表。有关如何实现这一点的任何想法?没有linq在映射之外。
我想要的sql看起来像
SELECT X.PHASE_S , PA.INTERVAL, PA.BOR, OP.DESCRIPTION
FROM GG.PROJ_PHASE_X X
inner join GG.PHASE PA
on X.PHASE_S=PA.PHASE_S
inner join GG.OPERATIONS OP
ON X.PHASE_S = OP.PHASE_S
WHERE OP.OPERATION_KIND = 'TASK';
映射:
public class MySectionMap : ClassMap<MySectionEntity>
{
public MySectionMap()
{
Schema("GG");
Table("PROJ_PHASE_X");
Id(x => x.PhaseS, "PHASE_S").GeneratedBy.TriggerIdentity();
References(x => x.Project).Column("PROJECT_S").Cascade.None().Not.LazyLoad().Not.Nullable();
Join("PHASE", m =>
{
m.Schema("GG");
m.Fetch.Join();
m.KeyColumn("PHASE_S");
m.Map(t => t.Interval).Column("INTERVAL");
m.Map(t => t.BorS).Column("BOR_S");
});
Join("OPERATIONS", m => // ONLY JOIN WHERE OPERATION_KIND EQUALS TASK?
{
m.Schema("GG");
m.Fetch.Join();
m.KeyColumn("PHASE_S");
m.Map(t => t.Description).Column("DESCRIPTION");
m.Map(t => t.OperationType).Column("OPERATION_KIND");
});
}
}
答案 0 :(得分:1)
Join
用于将多个表中的行简单合并为一个实体。你想要实现的目标有点复杂 - 你试图过滤掉一些值,而你在SQL中使用where
子句来做,而不是使用join
。
您有两个选择 - 在数据库中创建视图并将您的实体映射到视图(它的完成方式与表完全相同)。或者第二个选项,更多代码方是在地图级别上添加与where
子句相对应的限制:
public MySectionMap()
{
Schema("GG");
Table("PROJ_PHASE_X");
Join("PHASE", m => //...
Join("OPERATIONS", //...
Where("OPERATION_KIND = 'TASK'");
}
答案 1 :(得分:1)
问题是陈旧的,但无论如何。我遇到了同样的问题(遗留数据库,不允许更改架构)。如果它在where子句中,则nhibernate使用抛出错误的第一个表的别名。
我的解决方案是为连接定义视图,然后将视图用作连接表。无法进入where子句的列也会被映射(以便插入也可以工作)。在您的情况下,视图可能是:
CREATE VIEW FilteredOperations
SELECT OP.PHASE_S, OP.DESCRIPTION, OP.OPERATION_KIND
FROM GG.OPERATIONS OP
WHERE OP.OPERATION_KIND = 'TASK';
我的流利映射:
public class Agency : EntityBase
{
public const string AgencyRoleId = "F1776564-1CA0-11d5-A70C-00A0120802D7";
public Agency()
{
CountryId = "de";
LanguageId = "de";
}
public virtual string AgencyId { get; set; }
public virtual string Name { get; set; }
public virtual string UserDefinedName { get; set; }
public virtual string LanguageId { get; set; }
public virtual string CountryId { get; set; }
public virtual string RoleId
{
get
{
return AgencyRoleId;
}
set {}
}
}
public AgencyMap()
{
Table("mgmt_location_102");
Id(x => x.AgencyId, "LocationId").GeneratedBy.UuidHex("D");
Map(x => x.CountryId, "CountryId");
Map(x => x.LanguageId, "LanguageId");
Map(x => x.Name,"CommonName");
Join("mgmt_agency_ext", x=>
{
x.Optional();
x.KeyColumn("AgencyLocationId");
x.Map(y => y.UserDefinedName, "AgencyUserDefinedName");
});
Join("scs2.vAgencyRoles", x =>
{
x.KeyColumn("LocationId");
x.Map(y => y.RoleId, "RoleId").Not.Update();
});
}