fluent nhibernate HasOne WithForeignKey not working

后端 未结 6 841
故里飘歌
故里飘歌 2020-12-23 14:49

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 vi         


        
6条回答
  •  余生分开走
    2020-12-23 15:18

    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:

    References(x => x.Document)
        .TheColumnNameIs("ID")
        .PropertyRef(d => d.Task_ID);
    

    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.

提交回复
热议问题