2011-07-08 25 views
3

私はEF 4.1コードを使用しています。データを初期化する際に問題があります。下のコードでは、Clientで始まるモデルがあり、一連の関連オブジェクトが含まれていることがわかります。私は各オブジェクト型を読み込み、それを親に設定します。私のデータが私のオブジェクトにロードされた後、私は最上位のオブジェクトClientをデータベースに保存しようとします。私がこれを行うと、System.NullReferenceExceptionが発生します。EF 4.1コードの最初のデータベースの初期化System.NullReferenceExceptionデータのロード

EFはディープローディングしませんか?

データベースに各オブジェクトセットを保存する必要がありますか?最初に、それらのオブジェクトセットをデータベースに再関連付けしますか?これを行う必要がある場合、データを1つのクエリで実行できるようにする必要があるときに、データを読み込むのが大変なようです。

アドバイスや回答者に感謝します。

以下

は私のコードであり、その下に私の例外である:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data.Entity; 

namespace MyNameSpace 
{ 
    class Program 
    { 
    static void Main(string[] args) 
    { 
     Database.SetInitializer(new TimeServiceContextInitializer()); 
     TimeServiceContext db = new TimeServiceContext(); 
     var clients = db.Clients.ToList(); 

     foreach (var client in clients) 
     { 
      Console.WriteLine("Client: {0}\r\nNumber of Sites: {1}\r\n", client.Name, client.Sites.Count); 
     } 
    } 
} 

// Initialize Database 
public class TimeServiceContextInitializer : DropCreateDatabaseIfModelChanges<TimeServiceContext> 
{ 
    protected override void Seed(TimeServiceContext db) 
    { 
     List<Client> clients = new List<Client>(); 

     Client client = new Client(); 
     client.Name = "Achme Big Company"; 

     Site site = new Site(); 
     site.Name = "www.SampleSite.com"; 

     Project project = new Project(); 
     project.Name = "Schololarship Application Phase 1"; 
     project.Description = "Create an application that allows student to apply for scholarship in the www.SampleSite.com web site."; 
     project.DateCreated = DateTime.Now.AddDays(-15); 
     project.StartDate = DateTime.Now.AddDays(-5); 
     project.DeadlineDate = DateTime.Now.AddDays(45); 
     project.Status = Status.In_Progress; 
     project.FixedFee = 40500.00m; 
     project.SpecialNotes = "This project has a firm deadline due to the fact that marketing information is already set to go out to advertize applying for scholarships online through the web site"; 

     TimeEntry timeEntry = new TimeEntry(); 
     timeEntry.EmployeeName = "Brian Johns"; 
     timeEntry.TasksPerformed = "Started working on sceen mockups for the first page of the scholoarship application"; 
     timeEntry.TimeRecorded = DateTime.Now.AddDays(-4).AddHours(10); 
     project.TimeEntries.Add(timeEntry); /// <---- --------------------------- GET System.NullReferenceException Exception Here ----------- 

     timeEntry = new TimeEntry(); 
     timeEntry.EmployeeName = "Brian Johns"; 
     timeEntry.TasksPerformed = "Completed first section of form fields and started on the second section for the first page of the scholoarship application"; 
     timeEntry.TimeRecorded = DateTime.Now.AddDays(-4).AddHours(11.5); 
     project.TimeEntries.Add(timeEntry); 

     timeEntry = new TimeEntry(); 
     timeEntry.EmployeeName = "Brian Johns"; 
     timeEntry.TasksPerformed = "Decided we needed to regroup fields so started modifying form layout to work better on the first page of the scholoarship application"; 
     timeEntry.TimeRecorded = DateTime.Now.AddDays(-4).AddHours(13.25); 
     project.TimeEntries.Add(timeEntry); 

     timeEntry = new TimeEntry(); 
     timeEntry.EmployeeName = "Brian Johns"; 
     timeEntry.TasksPerformed = "Completed first form of the scholarship application. Started discussing the next form for step 2 of the scholarship application process"; 
     timeEntry.TimeRecorded = DateTime.Now.AddDays(-4).AddHours(14); 
     project.TimeEntries.Add(timeEntry); 

     site.Projects.Add(project); 
     client.Sites.Add(site); 

     db.Clients.Add(client); 
     db.SaveChanges(); 

     base.Seed(db); 
    } 
} 

// Context 
public class TimeServiceContext : DbContext 
{ 
    public DbSet<Client> Clients { get; set; } 
    public DbSet<Site> Sites { get; set; } 
    public DbSet<Project> Projects { get; set; } 
    public DbSet<TimeEntry> TimeEntries { get; set; } 
} 

// Model Starts Here 
public class Client 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public ICollection<Site> Sites { get; set; } 
    public DateTime DateCreated { get; set; } 
} 

public class Site 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public ICollection<Project> Projects { get; set; } 
    public int ClientId { get; set; } 
    public DateTime DateCreated { get; set; } 
} 

public enum Status { Not_Started, In_Progress, Completed }; 

public class Project 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Description { get; set; } 
    public DateTime StartDate { get; set; } 
    public DateTime DeadlineDate { get; set; } 
    public DateTime CompletionDate { get; set; } 
    public decimal FixedFee { get; set; } 
    public decimal HourlyRate { get; set; } 
    public Status Status { get; set; } 
    public string SpecialNotes { get; set; } 

    public ICollection<TimeEntry> TimeEntries { get; set; } 
    public int SiteId { get; set; } 
    public DateTime DateCreated { get; set; } 
} 

public class TimeEntry 
{ 
    public int id { get; set; } 
    public string EmployeeName { get; set; } 
    public string TasksPerformed { get; set; } 
    public DateTime TimeRecorded { get; set; } 
    public int InvoiceNumber { get; set; } 
    public int ProjectId { get; set; } 
} 
} 

Esception詳細: System.NullReferenceExceptionオブジェクトのインスタンスに設定されていないユーザコード メッセージ=オブジェクト参照によって未処理でした。 ソース=コンソール のStackTrace:CでMyNameSpace.TimeServiceContextInitializer.Seedで (TimeServiceContextデシベル):\ユーザーはジャスティン\ソースコントロール\ CoutoTimeService \コンソール\のProgram.csを\:System.Data.Entity.DropCreateDatabaseIfModelChanges 1.InitializeDatabase(TContext context) at System.Data.Entity.Database.<>c__DisplayClass2 1のライン51 .b_ 0(DbContext c) at System.Data.Entity.Internal.InternalContext。 System.Data.Entity.Internal.InternalContext.PerformDatabaseInitializationでSystem.Data.Entity.Internal.InternalContext.PerformInitializationAction(アクションアクション) (AT <> C _DisplayClass5.b_ 3() )System.Data.Entityで System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput入力) のInnerExceptionで.Internal.LazyInternalContext.b _4(InternalContext c)は :

答えて

1

は、プロジェクトのクラスにコンストラクタを追加

Project(){ 
TimeEntries = new HashSet<TimeEntry>(); 
} 

あなたはこのようなオブジェクトイニシャライザを使ってコードを少しプレティアにすることもできます:

Project project = new Project(){ 
    Name = "Schololarship Application Phase 1", 
    Description = "Create an application that allows student to apply for scholarship in the www.SampleSite.com web site.", 
    DateCreated = DateTime.Now.AddDays(-15), 
    StartDate = DateTime.Now.AddDays(-5), 
    DeadlineDate = DateTime.Now.AddDays(45), 
    Status = Status.In_Progress, 
    FixedFee = 40500.00m, 
    SpecialNotes = "This project has a firm deadline due to the fact that marketing information is already set to go out to advertize applying for scholarships online through the web site" 
}; 
+0

甘い赤ちゃんイエスこの回答は本当にありがとうございます!私はHashSetが何であるか分かりませんが、私のseedingは今働いています! – ledgeJumper

関連する問題