I have a Quest and QuestTemplate class like below
public class Quest{
public int ID {get;set;}
public virtual QuestTemplate QuestTemplate {get;set;}
public string Name{get;set;}
}
public class QuestTemplate{
public int ID {get;set;}
public QuestTemplate QuestTemplate {get;set;}
public string Name{get;set;}
public virtual Quest Quest{get;set;}
}
I create Quest and QuestTemplate like below in runtime
Quest q = new Quest();
q.Name = "Foo";
q.QuestTemplate = new QuestTemplate();
q.QuestTemplate.Name = "Bar";
context.Quests.Add(q);
context.SaveChanges();
It adds quest object and quest template object into related tables (Quests, QuestTemplates in this example). However the problem is that the Quest_ID column of quest template object in table is not set with quest object’s ID. Instead, it remains null. How can I resolve this problem?
P.S: I’m using EF5 with code first.
Best regards,
Kemal
Nowhere in the code did you specify the
QuestTemplateapplies to theQuestobject. The following code should work:Or you can map a one-to-one relationship.
Edit
Looked at this tonight and the reason for the relation isn’t mapping is in regards to the FK name. If you specify the FK in the fluent mapping, the relationship works as expected. Also, this type of 1-to-1 relationship requires either
QuestorQuestTemplatebe loaded first before the other (since it’s a required field) I randomly choseQuestTemplatebelow:I believe it has something to do with the section titled
Foreign Keyshere, but I’m still not clear on why this is. I have other relationships configured exactly the same way without identifying the FK.