简体   繁体   中英

When auto-mapping a collection with Fluent NHibernate, how do you make the child's foreign key to the parent nullable?

If I have a parent class:

public class Parent
{
    public Parent()
    {
        Children = new List<Child>();
    }

    IList<Child> Children {get; private set;}
}

and a child class like so:

public class Child
{
     public SomeThirdClass Friend {get; set;}
}

Whenever I let the Fluent NHibernate's automapper hit these guys, it makes the Child class have a non-nullable foreign key. I have altered a few automapping conventions and some overrides for certain classes, but for this particular pair only the Parent class has an override. The override does not specify how to map the collection part for the Parent class.

Is making a foreign key not-nullable in the child of a collection the default behavior, or have I F'ed something up?

How would one specify in a mapping override class that the child foreign key is nullable?

PEACE!

Have you tried this:

   public class ChildMap : IAutoMappingOverride<Child>
   {
       public void Override(AutoMapping<Child> mapping)
       {
           mapping.References(x => x.OtherThing)
               .Nullable();
       }
   }

If you want to make it the default for all your foreign keys, you can use this:

   public class NullableFKConvention : IReferenceConvention
   {
       public void Apply(IManyToOneInstance instance)
       {
           instance.Nullable();
       }
   }

I was able to solve the problem by removing a fluent mapping of a 4th GrandParent class, and allowing the automapper to map that class. Before I had not allowed the automapper to map the GrandParent class because I had a fluent mapping of that class. Somehow this conflict between fluent and auto mappings caused the foreign key in Child to be not-nullable.

I can't say that I completely understand what went wrong, so caution is advised when following my solution. But I can say that combining Fluent Mappings and Automappings definitely increases the complexity of debugging persistence issues.

Alternate Solution: I came across this problem again another two times, and I noticed that if I call KeyColumn(string columnName) in the IAutoMappingOverride for the Parent, the foreign key in the child class will default to Nullable, rather than Not-Null. Crazy Huh?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM