简体   繁体   中英

Fluent Nhibernate Aggregate objects mapping

Say I have the following class with an aggregation of an external class:

public class MyMovie
{
    public virtual string id{get;set;}
    public virtual Movie movie{get;set;}
}

//These classes are externally defined and cannot be changed.
public class Movie
{
    public string title{get;set;}
    public IList<Director> Directors{get;set;}
}

public class Director
{
    public string name{get;set;}
    public IList<Movie> DirectedMovies{get;set;}
}

The db schema for this would be three tables:

Movie(m_id, title)

Director(d_id, name)

Directs(m_id, d_id)

Is it possible to map this with fluent nhibernate? I just don't understand how this would be done with the many to many relation being in the external classes where I cannot map create a map class for Director as this does not define members as virtual.

Basically, your issue here is that you are trying to tell nhibernate to load objects, but it doesn't know anything about the objects. For instance, you are telling it MyMovie contains a Movie, yet it doesn't know what field Movie.title belongs to, and it doesn't know how to join in Director's with the movies because it is unmapped. So basically in order to pull this off without a mapping file, you need to use Criteria and result transformers to accomplish this (basically issuing a sql query and converting the results to objects via an on the fly mapping), you could encapsulate this logic in a function so it can be called in your code without being too messy, but other than that I can't see any other way around it. Check out this post, the code is not exactly what you are trying to do (because you will have to join in directors), but it is using the same tools you will have to use... http://ayende.com/blog/2741/partial-object-queries-with-nhibernate

Map your class MyMovie as usual, and use disable lazyloading of Movie and Director . Aftter all lazy-loading for many-to-many part should work as usualy, cause for collection laziness proxy is not need.

public class MyMovieMap : ClassMap<MyMovie>
{
    public MyMovieMap()
    {
        Id(x => x.id);
        References(x => x.movie);
    }
}

public class MovieMap : ClassMap<Movie>
{
    public MovieMap()
    {
        Not.LazyLoad();
        Id<int>("m_id");
        Map(x => x.title);
        HasManyToMany(x => x.Directors)
            .Table("Directs")
            .LazyLoad();
    }
}

public class DirectorMap : ClassMap<Director>
{
    public DirectorMap()
    {
        Not.LazyLoad();
        Id<int>("d_id");
        Map(x => x.name);
        HasManyToMany(x => x.DirectedMovies)
            .Table("Directs")
            .LazyLoad();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM