2

I've not been able to find an answer to this question.

Say you have ClassA:

public class ClassA {
    public Guid Id { get; set; }
    public IList<ClassB> { get; set; }
}

And ClassA has nested a collection of ClassB objects:

public class ClassB {
    public Guid Id { get; set; }
    public string SomeProperty { get; set;}  
}   

Is there any way using NHibernate to map these objects to tables, generate the schemas but NOT have a foreign key relationship created for the ClassB table?

UPDATE

Figured the solution - when mapping by code:

Bag<ClassA>(x => x.ClassB, 
            collectionMapping => {
                collectionMapping.Table("ClassB");
                collectionMapping.Cascade(Cascade.All);
                collectionMapping.Key(key => { 
                      key.Column("ClassAId");
                      key.ForeignKey("none");
                 });
                collectionMapping.Lazy(CollectionLazy.NoLazy);
           },
           mapping => mapping.OneToMany(x => {
                 x.Class(typeof(ClassB));
           })
      );
David
  • 1,731
  • 24
  • 37
  • Is it the constraint you don't want or the fkey field? How do you propose that the rows from ClassBTable be identified as belonging to a particular ClassA without a reference of some sort? – Rytmis Jul 12 '12 at 10:22
  • To clarify, `TableB` will still have a `ClassAId` column, I'm fine with that. I just dont want that `ClassAId` comumn to be generated with a foreign key constraint. – David Jul 12 '12 at 10:27
  • possible duplicate of [Prevent Nhibernate schemaexport from generating foreign key constraints on has many relationship](http://stackoverflow.com/questions/2826725/prevent-nhibernate-schemaexport-from-generating-foreign-key-constraints-on-has-m) – Rytmis Jul 12 '12 at 10:35
  • @Rytmis: Annoyingly that answer is relevant to Fluent NHibernate :( I'm not desperate enough yet to go trawling through their source code to find out what `ForeignKeyConstraintName` does. – David Jul 12 '12 at 10:38

1 Answers1

4

i think that if you set the collection mapping as inverse="true" the schema generation tool does not create the FK.

edit: as the comment points out (didn't know that!) with xml mapping maybe this works:

<many-to-one name="Bar" foreign-key="none" />
Jaguar
  • 5,929
  • 34
  • 48
  • Neither of these are working for me. I think the problem is I am mapping the collection as a bag. – David Jul 12 '12 at 12:06
  • 1
    I got it working finally! You were right I was just getting it wrong because of if difference between the XML mapping and the mapping by code. This: `key.ForeignKey("none");` removes the foreign key. – David Jul 12 '12 at 12:39