Whenever I load a Task class, the Document property is always null, despite there being data in the db.
Task class:
public class Task { public virtual Document Document { get; set; }
Task Mapping override for AutoPersistenceModel:
public void Override(AutoMap<Task> mapping) { mapping.HasOne(x => x.Document) .WithForeignKey('Task_Id');
As you can see form what NHProf says is being run, the join condition is wrong, the WithForeignKey doesnt seem to take effect. In fact, i can write any string in the above code and it makes no difference.
FROM [Task] this_ left outer join [Document] document2_ on this_.Id = document2_.Id
It should be:
FROM [Task] this_ left outer join [Document] document2_ on this_.Id = document2_.Task_Id
If i hack the data in the db so that the ids match, then data is loaded, but obviously this is incorrect – but at least it proves it loads data.
Edit: rummaging in the fluent nhib source to find the XML produces this:
<one-to-one foreign-key='Task_Id' cascade='all' name='Document' class='MyProject.Document, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' />
Edit: heres the schema:
CREATE TABLE [dbo].[Document]( [Id] [int] IDENTITY(1,1) NOT NULL, [Task_Id] [int] NOT NULL, CREATE TABLE [dbo].[Task]( [Id] [int] IDENTITY(1,1) NOT NULL,
Anyone got any ideas?
Thanks
Andrew
I think the problem here is that the ‘HasOne’ convention means that you are pointing at the other thing(the standard relational way to say ‘Many To One’/’One to One’); By putting a Task_ID on the document the actual relationship is a HasMany but you have some kind of implicit understanding that there will only be one document per task.
Sorry – I don’t know how to fix this, but I will be interested in seeing what the solution is (I don’t use NHibernate or Fluent NHibernate, but I have been researching it to use in the future). A solution (from someone with very little idea) would be to make Documents a collection on Task, and then provide a Document property that returns the first one in the collection (using an interface that hides the Documents property so no one thinks they can add new items to it).
Looking through documentation and considering eulerfx’s answer, Perhaps the approach would be something like:
EDIT: Just so this answer has the appropriate solution: The correct path is to update the database schema to match the intent of the code. That means adding a DocumentID to the Task table, so there is a Many-To-One relationship between Task and Document. If schema changes were not possible, References() would be the appropriate resolution.