4

If I specify PropertyRef on References (Many to One) - it eagerly fetches all related records:

References(x => x.Panel).PropertyRef(x => x.Code).Not.Insert().Not.Update();

Can I disable that N + 1 select problem?

Here I can see that this problem is known, but is there any workaround? Lazy loading not working for many-to-one relationship when mapping to a non-key field using property-ref

Community
  • 1
  • 1

1 Answers1

3

There is a workaround. But only becuase your many-to-one is readonly (and we do not have to care about insert/udpate issues later). How? By introducing a virtual entity e.g. PanelView

// Readonly mapping, virtual class
// which ID role is playing column panel_CODE
public PanelViewMapping()
{
    Table("panel-table");
    Id(x => x.Code)
      .Column("panel_CODE")
      .GeneratedBy.Assigned();
    ...

Now, we have to adjust the POCO entity:

// instead of this
// public virtual Panel Panel { get; set; }
// we will have this
public virtual PanelView Panel { get; set; }

And then we can use it as a primary key mapping:

References(x => x.Panel)
  //.PropertyRef(x => x.Code)
 .Not.Insert()
 .Not.Update();

And all the features (lazy loading) will work properly.

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Wow, this looks correct and promising. I'll check it tomorrow. – Aurimas Neverauskas Feb 15 '15 at 18:17
  • Yeah, for legacy DB it is the way... wish it would help you. Of course, there are some issues if the relation should be editable. But for readonly... it will work. I tested ;) Good luck with NHibernate sir ;) – Radim Köhler Feb 15 '15 at 18:19