如何在Fluent nHibernate中进行一对一映射以尊重父/所有者对象的批处理?

时间:2014-01-08 02:41:54

标签: c# nhibernate fluent-nhibernate

我有以下映射

public class FilmMap : ClassMap<Film>
{
    public FilmMap()
    {
        Id(x => x.FilmId, "film_id");
        Map(x => x.Description);
        base.HasMany<FilmActor>(x => x.FilmActor).BatchSize(100);
    }
}

public class FilmActorMap : ClassMap<FilmActor>
{
    public FilmActorMap()
    {
        Table("film_actor");
        CompositeId()
            //.KeyReference(x => x.Actor, "actor_id")
            .KeyProperty(x => x.ActorId, "actor_id")
            .KeyProperty(x => x.FilmId, "film_id");
        Map(x => x.LastUpdate, "last_update");
        References<Actor>(x => x.Actor, "actor_id"); //.Fetch.Join();
    }
}

public class ActorMap : ClassMap<Actor>
{
    public ActorMap()
    {
        Id(x => x.ActorId, "actor_id");
        Map(x => x.FirstName, "first_name");
    }
}

运行它的代码

var films = session.QueryOver<Film>().Where(x => x.FilmId < 5).Future();
foreach (var film in films)
{
   foreach (var actor in film.FilmActor) //Does a batch query
   {
      Console.Write(actor.Actor.FirstName + ", "); 
      //For each actor it fetches the record from db
   }
}

当我从Actor中为每个actor获取数据时,会触发一个查询。 我希望nHibernate也能为Actor调用In-Query。这看起来像下面的

SELECT actor_id, first_name
FROM actor
WHERE actor_id in (actor_id batch collected from film.FilmActor )

我不想在批处理中使用filmActor和Actor之间的连接,因为这证明是昂贵的。

如何加载一对一地图/参考以进行批量提取

1 个答案:

答案 0 :(得分:2)

你快到了。您完成的所有batch-size映射都是正确的,但BatchSize不仅可以设置为集合,还可以设置为classes

public ActorMap()
{
    Id(x => x.ActorId, "actor_id");
    Map(x => x.FirstName, "first_name");
    BatchSize(100);
}

注意:我的经验是几乎每个班级都使用它,完全出于你在这里提到的原因...我们将通过更有效的批处理获得延迟加载