开发者

Custom reference mapping in Fluent Nhibernate

In my database, I have two tables, one logically referencing other, but with no foreign key defined (I cannot control the database, so have to live with that). E.g.:

Table1 (
    Table1Id int,
    Column1 int,
    Column2 int
)

Table2 (
    Table2Id int,
    Column1FromTable1 int,
    Column2FromTable1 int
)

Suppose there is guarantee that (Column1, Column2) pair is unique for Table1.

In the code, I want to define HasMany mapping for Table1, like this:

public class Table1
{
    public int Id
    {
        get;
        set;
    }

    public IEnumerable<Tab开发者_C百科le2> Table2s
    {
        get;
        set;
    }
}

public class Table2
{
    public int Id
    {

    }

    public Table1 Table1
    {
        get;
        set;
    }

}

public class Table1Map : ClassMap<Table1>
{
    public Table1Map()
    {
        Id(x => x.Id).Column("Table1Id");
        HasMany(x => x.Table2s); //What next?
    }
}

What do I have to do for that? What methods of OneToManyPart can I use to define the reference?

In simple words, with Fluent NHibernate, how do I tie in the code entities that are not tied in the database? The problem is also in the complex key that I have to use here.

Again, I cannot change the database in this case, which would be my natural choice otherwise.


You will need to map Col1 & Col2 as a composite key like that:

public class Table1Map : ClassMap<Table1>
{
    public Table1Map()
    {
        UseCompositeId()  
                .WithKeyProperty( x => x.Column1 , "Column1" )  
                .WithKeyProperty( x => x.Column2 , "Column2" );  
        HasMany(x => x.Table2s)
                 .WithKeyColumn( "Column1FromTable1" )  
                 .WithKeyColumn( "Column2FromTable1" ) ;
        Map(x => x.Id).Column("Table1Id");
    }
}

and in the mapping for Table2:

public class Table2Map : ClassMap<Table2>
{
    public Table2Map()
    {
        Id(x => x.Id).Column("Table2Id");
        References(x => x.Table1)
                 .WithColumns( "Column1FromTable1", "Column2FromTable1" ) ;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜