tags:

views:

68

answers:

3

Hi,

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

A: 

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.

David
thanks for the response. i thought about using dto's but i didn't really want to have to maintain two objects. i just came up with the above example to get my question out. the actual database that i am trying to use (for work) has hundreds of tables which would mean hundreds of entities. i guess i could use dto's just for the special needs scenarios and stick with standard entities for everything else. i thought it might be a common scenario.
Yes, DTOs are extra objects but like you have rightly said yourself you can use a mix for thoses special cases. It does not have to be 100% DTO usage.
David
+1  A: 

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.

MrTelly
by reading ayende's post i assume that my situation is not possible. it looks like the PK on both referenced tables has to be the same for it to work. or am i reading that wrong?
A: 

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"

Paco