Join table in mapping with inverse FK

这一生的挚爱 提交于 2019-12-11 07:54:36

问题


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?


回答1:


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; }
}



回答2:


Maybe you should use a References (many-to-one) mapping instead.

References(x => x.Other, "OTHER_ID")
    .Fetch.Join()


来源:https://stackoverflow.com/questions/9923915/join-table-in-mapping-with-inverse-fk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!