我有2个类,如下所示。Entity Framework外键null作为实体输入时保留为空
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。我怎么能想出这个问题?
它没有性能问题吗?因为在这种情况下,每次添加对象时都必须保存更改 – kkocabiyik 2012-04-15 18:49:34
您可以尝试省略第一个SaveChanges()方法。我认为,性能问题可能会在这种情况下解决。 – sarwar026 2012-04-15 18:51:16
如果我省略了第一个SaveChanges,那么我的代码和您的代码之间有什么区别?我的意思是不应该通过设置Quest_ID自动将QuestLocation对象实例设置为查询吗? – kkocabiyik 2012-04-15 18:54:58