外键关系,相关对象在DbContext中没有正确存储?

时间:2012-12-06 09:07:17

标签: c# wpf wcf entity-framework

尽管我完全不熟悉.NET堆栈,但我还是设法开发了一个涉及以下技术的小型N层应用程序:

WPF - > WCF - >实体框架 - > SQL Server

我的疑问主要是关于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();

重点是:在处理上下文&amp;做一个查询,如:context.Problems.ToList()... problem1&amp; problem2将其导航属性(Worker,Work)分配给Null。存储了WorkerId和WorkId,但在问题实体中没有相关的对象。

我错过了什么吗?

非常感谢您的回答!

1 个答案:

答案 0 :(得分:1)

是的,你需要做

context.Problems.Include(p=>p.Work).ToList() 

以便在新环境下重新加载子项时填充子项。