儘管我完全新的.NET堆棧,我總算制定了小的N層應用程序包括以下技術:外鍵關係,相關對象在DbContext中沒有正確存儲?
WPF - > WCF - >實體框架 - > SQL服務器
我懷疑主要是關於Entity Framework如何管理導航屬性的分配。我會把我的數據合約代碼拿到球羅林......
[DataContract]
public class Problem
{
[DataMember]
public int ProblemId { get; set; }
[DataMember]
public String Title { get; set; }
[DataMember]
public String Description { get; set; }
[DataMember]
public int WorkerId { get; set; }
[DataMember]
public int WorkId { get; set; }
[DataMember]
[ForeignKey("WorkerId")]
public virtual Worker Worker { get; set; }
[DataMember]
[ForeignKey("WorkId")]
public virtual Work Work { get; set; }
}
[DataContract]
public class Worker
{
[DataMember]
public int WorkerId { get; set; }
[DataMember]
public String Name { get; set; }
[DataMember]
public virtual ICollection<Problem> Problems { get; set; }
}
[DataContract]
public class Work
{
[DataMember]
public int WorkId { get; set; }
[DataMember]
public String Name { get; set; }
[DataMember]
public virtual ICollection<Problem> Problems { get; set; }
}
在我種方法,我做了以下內容:
Work Work1 = new Work()
{
WorkId = 1,
Name = "Work1"
};
Worker emp1 = new Worker()
{
WorkerId = 1,
Name = "Worker1"
};
Problem Problem1 = new Problem()
{
...
WorkId = 1,
WorkerId = 1
};
Problem Problem2 = new Problem()
{
...
Work = Work1,
Worker = emp1
};
//add objects to the context
context.Works.Add(Work1);
context.Workers.Add(emp1);
context.Problems.Add(Problem1);
context.Problems.Add(Problem2);
//added just for testing
Problem1.Work = Work1;
Problem1.Worker = emp1;
//finally: save changes
context.SaveChanges();
而且一點是:處置後上下文&正在執行查詢,如:context.Problems.ToList()... both problem1 & problem2將其導航屬性(Worker,Work)分配給Null。 WorkerId和WorkId存儲在問題實體中,但沒有其相關的對象。
我錯過了什麼嗎?
非常感謝您提前回答您的問題!
請注意,我以兩種不同的方式創建「問題」對象(通過他們的ID和他們的導航屬性直接分配他們相關的工作和工作人員)。這不是一個錯字,或者錯誤,或者其他什麼。我只是想知道爲什麼會發生這種情況,以及初始化「問題」的兩種方式......結果是一樣的! ;) –