开发者

NHibernate - mapping entity from multiple database tables

开发者 https://www.devze.com 2022-12-15 16:28 出处:网络
Is it possible to map an entities properties from different database tables? Say you had the below data model...

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; }
    p开发者_运维百科ublic 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


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.


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.


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"

0

精彩评论

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