Am I doing many to many incorrectly when using flu

2020-02-02 03:08发布

问题:

I have two main entities (db tables)

  1. Project
  2. Application

I have a bridge tabled called ProjectApplication with 3 col (Id, ProjectId, ApplicationId)

A project can have many applications. An application can below to many different project

Your basic many to many mapping

Currently this is what i have setup in my fluent nhibernate mapping files

 public class ProjectMap
 {
        HasMany(x => x.ProjectApplications)
      .AsBag().Inverse().Cascade.AllDeleteOrphan().Fetch.Select().BatchSize(80);
 }

 public class ApplicationMap
 {
      HasMany(x => x.ProjectsApplications)
          .AsBag().Inverse().Fetch.Select().BatchSize(50);

 }

Is there any downside to this as i see there is a HasManyToMany syntax so I am not sure if it makes a difference in terms of the Queries that are generated or performance, etc

Please advise

回答1:

In general there are two approaches, as you've correctly mentioned:

  • explicit mapping of the pairing object, resulting in one-to-many and many-to-one
  • implicit mapping without any knowledge of the underlying table using many-to-many

I (my personal statement) would avoid many-to-many in almost any scenario (while in some very rare, really admin object scenario could be used).

Here are some of my tries, to explain that:

  • How to create NHibernate HasManyToMany relation
  • many-to-many with extra columns nhibernate
  • Nhibernate: How to represent Many-To-Many relationships with One-to-Many relationships?

To add more here, I would firstly mention, that with many-to-many we are loosing the pairing object from the model. Forever. So, once our customer will come and ask: please, make one of my relations Main, or introduce the Sorting - we simply cannot. The relation is as it is. No way how to extend it.

And secondly, and most likely - very likely: our customer will come and ask: Could you create a filter for me, selecting only Projects which are related to Application having some setting set to true AND ...

And that would be a bit challenging in many-to-many case.

The scenario with explicit pairing object brings more overhead with that third Entity. But could be converted into Subqueries

There are some examples of the Subquery power:

  • Query on HasMany reference
  • Is it possible to query all objects that have one or more possible children using NHibernate?

Well, that is my point of view. Not saying it is correct. But my experience shows, that with explicit pair object mapping we are ready for extensions as well as for complex queries.