3

I have 2 tables in my database:

  • Team Table (Id, Name, WebsiteId (nullable))
  • WebSite Table (Id, Name)

A website can be aligned with a team but doesn't have to be. A team can be aligned to a website but doesn't have to. So the relationship between the two is both one or none on either side.

Originally, The only way I could see of doing this is to create a one to many mapping by doing this:

WebsiteMap class

 HasMany(x => x.Teams).AsBag().Inverse().Fetch.Select().BatchSize(50);

TeamMap class

 References(x => x.WebSite).Nullable();

but to correct enforce a 1:1 mapping, I have to do this in my website class I have this code:

    public virtual Team Team
    {
        get
        {
            return Teams.FirstOrDefault();
        }
    }

How can I correctly describe this relationship in the mapping layer itself to avoid having to do this conversion?

The key thing here is that one of these tables is not a slave of the other. All of the examples I see on the internet around 1:1 mappinges with fluent nhibernate assume the second table wouldn't exist without the first (like User table and UserPreferences table) but that is not my situation.

In my example above, since its nullable on both side neither is master or slave?
What is the correct way to map this in fluent nhibernate?

leora
  • 188,729
  • 360
  • 878
  • 1,366
  • Is this not just a one-to-one mapping on both sides with nullable columns for the relationships? – starlight54 Nov 19 '16 at 17:54
  • yes, but i don't see how that answers the question – leora Nov 19 '16 at 19:02
  • There's an answer on how to do a One-to-One using Fluent here, I'm assuming that just adding `Nullable()` on both ends would cover your scenario. http://stackoverflow.com/questions/6085568/how-to-do-a-fluent-nhibernate-one-to-one-mapping#answers – starlight54 Nov 19 '16 at 20:40
  • @starlight54 - the problem is that example has a "Master Slave" relationship where Setting would only exist if there was a student. As i mentioned above I don't have that so I wouldn't want deleting either side affect the other – leora Nov 19 '16 at 22:37

1 Answers1

1

This is not specifically for NHibernate, but a solution that should work regardless, but you could create a third table containing the relationship between the two.

Both the WebSite Table and the Team Table would then have a one-to-none relationship with the Relationship Table.

Then you could use a relationship such as the one mentioned in the comments with this middle table.

So: Team_WebSite (TeamId, WebSiteId)

Community
  • 1
  • 1
mrks
  • 13
  • 1
  • 7