Problems with mapping foreign keys
Hi,
I'm new to nHibernate and Fluent nHibernate and I'm looking for some help.
I've got the following set up:
Table 1:
QuestionTypeID
QuestionType
IsActive
SortOrder
Table 2:
QuestionID
Question
IsActive
SortOrder
QuestionTypeID
My mapping files look like this:
Table 1 Map:
Table("QuestionTypes");
LazyLoad();
Map(x => x.IsActive).Not.Nullable();
Map(x => x.QuestionType).Length(50).Not.Nullable();
Map(x => x.SortOrder).Not.Nullable();
Id(x => x.QuestionTypeID).GeneratedBy.Identity();
Table 2 Map:
Table("Questions");
LazyLoad();
Map(x => x.IsActive).Not.Nullable();
Map(x => x.Question).Length(1000).Not.Nullable();
Map(x => x.SortOrder).Not.Nullable();
Id(x => x.QuestionID).GeneratedBy.Identity();
References(x => x.QuestionTypeID).Column("QuestionTypeID");
Whenever I try to run a query such as
IList results = session.CreateQuery("from Questions").List();
I get the following error:
An association from the table Questions refers to an unmapped class: System.Int32
I'm really not sure how to proceed. Any help would be greatly appreciated.
Thanks.
Support Staff 2 Posted by James Gregory on 27 Jul, 2010 09:13 PM
You don't want to be mapping your Id properties directly, instead you should be mapping actual entity references. In fact, your foreign keys shouldn't be in your entities at all.
References(x => x.QuestionTypeID)
should beReferences(x => x.QuestionType)
whereQuestionType
is a property on your entity of the actual target entity rather than it's key.3 Posted by martindalec on 28 Jul, 2010 01:34 PM
Hi James,
Thank you for posting but I'm still confused. I used the program located at http://nmg.codeplex.com/ to generate my templates. Is this tool just generating them incorrectly? Do you have any recommendations for a tool to autogenerate the mappings?
I resorted to a tool to generate them as I'm ramping up for a project that will have over 200 tables that will need mappings created for them.
Support Staff 4 Posted by Paul Batum on 07 Aug, 2010 12:09 AM
I haven't used the tool you linked to but James is quite right in that it
does not make sense to use References(x => x.SomeID).
Have you tried using automapping? If your domain objects and database schema
align closely enough for your to consider using any sort of automated tool,
then I think its worth spending some time on evaluating automapping:
http://wiki.fluentnhibernate.org/Auto_mapping
On Wed, Jul 28, 2010 at 11:36 PM, Chris <
***@tenderapp.com<tender%***@tenderapp.com>
> wrote: