Fluent NHibernate : How to map a 'Foreign Key&

2019-02-15 22:17发布

问题:

I'm starting to develop with Fluent NHiberate, and I was wondering how I create a defined 'Foreign Key' relationship in my Mapping class.

Here's my class. These classes are a one-to-one with associated tables.

public class Song
{
    public virtual int SongID{ get; private set; } //Primary Key
    public virtual int SongArtistID { get; set; } //Foreign Key mapping to 'Artist.ArtistID'
    public virtual string Title { get; set; }
}

public class Artist
{
    public virtual int ArtistID{ get; private set; } //Primary Key
    public virtual int ArtistName{ get; set; }
}

public class SongMapping : ClassMap<Song>
{
    SongMapping()
    {
        Id(c => c.SongID);//.GeneratedBy.HiLo("sermon"); is HiLo generator good?
        Map(c => c.SermonArtistID).Not.Nullable(); //How is this mapped to 'Artist.ArtistID'??
        Map(c => c.Title).Not.Nullable().Length(50);
    }
}

In my mapping file, I want to create a defined foreign key relationship in my Song class SongArtistID column, which will define a foreign key to the ArtistID column in the Artist table/class.

回答1:

Here you go:

public class Song
{
    public virtual int Id { get; private set; } 
    public virtual Artist Artist { get; set; } 
    public virtual string Title { get; set; }

    public class SongMap : ClassMap<Song>
    {
        SongMap()
        {
            Id(c => c.Id);
            References(c => c.Artist);  // Yes, that's all.
            Map(c => c.Title).Not.Nullable().Length(50);
        }
    }
}

That being said, it's easier using the Automapper configuration.



回答2:

I have things to work with identifiers via next (tested on my entities, here just renamed things and no run was done, please consider it as patter to try):

References<Artist>(x => x.SongArtistID ).Column("SongArtistID").ForeignKey("ArtistID");