user243575
user243575

Reputation: 11

NHibernate - mapping entity from multiple database tables

Is it possible to map an entities properties from different database tables? Say you had the below data model...

[dbo.Albums]              [dbo.Songs]                [dbo.Artists]
AlbumID int (PK)          SongID int (PK)            ArtistID int (PK)
AlbumName nvarchar(100)   AlbumID int                ArtistName nvarchar(100)
.                         SongName nvarchar(50)      .
.                         Duration int               .
.                         ArtistID int               .
.                         .

Required entity:

public class Album
{
    public virtual int AlbumID { get; private set; }
    public virtual string AlbumName { get; set; }
    public List<Song> songs { get; set;}
}

public class Song
{
    public virtual int SongID { get; private set; }
    public virtual int AlbumID { get; set; }
    public virtual string SongTitle { get; set; }
    public virtual int Duration { get; set; }
    public virtual ArtistID { get; set; }
    public virtual ArtistName { get; private set; }      <- from different table, read only
}

I know I should probably be creating an Artists entity and attaching that to the Song entity but if the Artists table had lots of columns and all I needed was the ArtistName what's the point in returning all the extra data across the wire when it's not going to be used or updated? I only want the ArtistName for display purposes only.

Thanks, FJ

Upvotes: 1

Views: 1020

Answers (3)

Paco
Paco

Reputation: 8381

It has no use to send the extra information over the wire, but why are you worried about that? I doubt you can even measure the difference when you use this in a non-batching scenario.

"Premature performance optimization is the root of all evil"

Upvotes: 0

MrTelly
MrTelly

Reputation: 14875

Try Ayende's answer to your question, not sure if that code is in the main trunk of NHibernate now but it delivers what you need.

Upvotes: 1

David
David

Reputation: 3609

In my opinion you should have a Songs entity and an Artists entity. Get the song you required along with the artist details and create a song DTO (Data Transfer Object).

The SongDTO will contain all the properties that you require.

Extract the required data and assemble a SongDTO for pushing over the wire.

Upvotes: 0

Related Questions