Fluent Nhibernate HasManyToMany both sides with noop map
-
25-09-2019 - |
Question
I am trying to map a POCO as a many-to-many relationship. I do not want a property on Behavior that Contains BehavioralEvents. I'm pretty sure the Many-to-Many mapping has to be in both places, however I don't want the corresponding property on my Behavior class.
I have heard you can use a no-op access operator but im not sure how to do it in Fluent Nhibernate.
Please advise:
public class BehavioralEvent : AggregateRoot
{
protected internal IList<Behavior> Behaviors { get; private set; }
public BehavioralEvent()
{
Behaviors = new List<Behavior>();
}
}
Behavior Class (No reference back to BehavioralEvent)
public class Behavior : AggregateRoot
{
protected internal virtual string Name { get; private set; }
protected internal virtual string Definition { get; private set; }
public Behavior(string name, Guid id)
{
this.Id = id;
this.Name = name;
}
protected Behavior(){}
}
BehavioralEventClassMap:
public class BehavioralEventClassMap : ClassMap<BehavioralEvent>
{
public BehavioralEventClassMap()
{
Id(x => x.Id, "BehavioralEventId").GeneratedBy.Assigned();
HasManyToMany(x => x.Behaviors)
.Cascade.All()
.Table("BehaviorData")
.ParentKeyColumn("BehavioralEventId")
.ChildKeyColumn("BehaviorId");
}
}
BehaviorClassMap:
public class BehaviorClassMap : ClassMap<Behavior>
{
public BehaviorClassMap()
{
Table("Behaviors");
Id(x => x.Id, "BehaviorId").GeneratedBy.Assigned();
Map(x => x.Name).Not.Nullable();
Map(x => x.Definition);
}
}
Solution
You do not need to map it from both sides.
I have various mappings like this:
HasManyToMany(x => x.SomeCollection).Table("MappingTable").ParentKeyColumn("ParentKey").ChildKeyColumn("ChildKey").Cascade.AllDeleteOrphan();
Works like a charm! Map it as Collection or Set (see http://www.codinginstinct.com/2010/03/nhibernate-tip-use-set-for-many-to-many.html).
OTHER TIPS
If you do not need from Behavior then do not add in mapping. If you need and do not want to put operation then use Cascade.None()