0

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

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

我的疑问主要是关于实体框架如何管理导航属性的分配。我将把我的数据合同代码放在一起,让球滚起来......

[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; }
}

在我的 Seed 方法中,我正在执行以下操作:

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() ...问题1和问题2都将其导航属性(Worker,Work)分配给Null。WorkerId 和 WorkId 被存储,但问题实体中没有它的相关对象。

我错过了什么吗?

非常感谢您的回答!

4

1 回答 1

1

是的,你需要做

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

为了在新上下文下重新加载子项时填充子项。

于 2012-12-06T09:11:52.260 回答