加入与逆FK映射的表 [英] Join table in mapping with inverse FK
问题描述
表MY_ENTITY
ID:PK
OTHER_ID:FK表格其他
表格其他
ID:PK
COL:我想要
的列
我的实体看起来像这样:
class MyEntity:Entity
{
public virtual Column {get;组; }
}
我的自动映射重写如下所示:
$ b
mapping.IgnoreProperty(x => x.Column);
mapping.Join(OTHER,x => x.KeyColumn(ID)。Optional()
.Map(y => y.Column,COL);
这工作正常并且执行没有问题,但连接是错误的。
它创建一个SQL语句,将 MY_ENTITY
的PK连接到 KeyColumn
中指定的列 OTHER
。
select .. 。from MY_ENTITY e left outer join OTHER o on e.ID = o.ID
然而,我需要连接如下:
select ... from MY_ENTITY e left outer join OTHER o on e.OTHER_ID = o。 ID
如何实现这个功能?
您必须添加 OtherId
属性到 MyEntity
不必公开,只是为了映射),并在Join Key中使用 PropertyRef
pping(这是通过代码映射的方法名称;它是XML中的 property-ref
,你必须查看Fluent)
或者,map 其他
作为实体,并在 MyEntity
中使用 Reference
。您可以级联所有,所以它与MyEntity一起被持续/删除。
class MyEntity
{
public virtual PropertyType Property
{
get
{
EnsureOther();
返回Other.Property;
}
set
{
EnsureOther();
other.Property = value;
void EnsureOther()
{
if(Other == null)
Other = new Other();
}
public virtual其他{get;组; }
}
class其他
{
public virtual PropertyType Property {get;组; }
}
Assume I have two tables:
Table MY_ENTITY
ID: PK
OTHER_ID: FK to table OTHER
Table OTHER
ID: PK
COL: The column I want
My entity looks like this:
class MyEntity : Entity
{
public virtual Column { get; set; }
}
My auto-mapping override looks like this:
mapping.IgnoreProperty(x => x.Column);
mapping.Join("OTHER", x => x.KeyColumn("ID").Optional()
.Map(y => y.Column, "COL");
This works fine and executes without problems, but the join is wrong.
It creates an SQL statement that joins the PK of MY_ENTITY
to the column specified in KeyColumn
in the table OTHER
. Something along the lines of:
select ... from MY_ENTITY e left outer join OTHER o on e.ID = o.ID
However, I need the join to be like this:
select ... from MY_ENTITY e left outer join OTHER o on e.OTHER_ID = o.ID
How to achieve this?
You'll have to add an OtherId
property to MyEntity
(it doesn't have to be public; it's just for mapping) and use PropertyRef
in the Join Key mapping (that's the method name in mapping by code; it's property-ref
in XML, you'll have to look it up for Fluent)
Alternatively, map Other
as an entity and use a Reference
in MyEntity
. You can cascade all, so it get's persisted/deleted together with MyEntity.
Then, just project the referenced property (which will not be mapped in MyEntity):
class MyEntity
{
public virtual PropertyType Property
{
get
{
EnsureOther();
return Other.Property;
}
set
{
EnsureOther();
other.Property = value;
}
}
void EnsureOther()
{
if (Other == null)
Other = new Other();
}
public virtual Other { get; set; }
}
class Other
{
public virtual PropertyType Property { get; set; }
}
这篇关于加入与逆FK映射的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!