实体框架外键null保留为实体输入

时间:2012-04-15 18:36:28

标签: c# asp.net-mvc entity-framework entity-framework-4

我有2个类,如下所示。

public class Quest
{
    public int ID{ get;set; } 

    public string Objective
    {
        get;
        set;
    }

    public DateTime StartDate
    {
        get;
        set;
    }

    public string Story
    {
        get;
        set;
    }

    public virtual QuestLocation Location
    {
        get;
        set;
    }
}
    public class QuestLocation
{
    public DateTime CreateDate
    {
        get;
        set;
    }

    public int ID
    {
        get;
        set;
    }

    public double Latitude
    {
        get;
        set;
    }

    public double Longitude
    {
        get;
        set;
    }

    public virtual Quest Quest
    {
        get;
        set;
    }

}

我创建了一个新的Quest实例,之后我设置了Quest的location属性,只是创建了一个新的QuestLocation类实例。

   Question q = new Question();
   q.StartDate = DateTime.Now;
   q.Objective = "foo";
   q.Location = new QuestLocation(){ CreateDate = DateTime.Now, Latitude = 10 , Longitude = 10 };

   And add newly created Quest into Database :
   DataContext.Quests.Add(q);
   DataContext.SaveChanges();

当我查看我的数据库时,到目前为止已初始化的每个对象都已创建。但是,QuestLocation的外键“Quest_ID”仍为NULL。我怎么能想出这个问题呢?

2 个答案:

答案 0 :(得分:0)

您必须在questlocation对象上设置quest_id。 将数据库中的外键字段(quest_id)设置为非null也是一种很好的做法。

答案 1 :(得分:0)

Question q = new Question();
QuestionLocation qL = new QuestLocation(){ CreateDate = DateTime.Now, Latitude = 10 , Longitude = 10 };
q.StartDate = DateTime.Now;
q.Objective = "foo";
q.Location = qL;

//And add newly created Quest into Database :
DataContext.QuestLocations.Add(qL);
DataContext.SaveChanges();

DataContext.Quests.Add(q);
DataContext.SaveChanges();