Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6112929
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T14:48:03+00:00 2026-05-23T14:48:03+00:00

I am using EF 4.1 Code First and I am having trouble initializing my

  • 0

I am using EF 4.1 Code First and I am having trouble initializing my data the way I think I should be able to. In my code below, you will see that I have a model that starts with Client and it contains a series of related objects. I load each object type and set it into its parent. After my data is loaded into my objects, i try to save the top level object Client to the database. When I do this I get a System.NullReferenceException.

Will EF not do deep loading?

Do I need to save each object set to the database first them relate them to eachother a resave them to the database? If I have to do this, it seem like it would be a lot of conections to load my data when it should be able to be performed in one query.

Any advice or answrs would be appreciated.

Below is my code, and below that is my exception:

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 Details:
System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
Source=Console
StackTrace:
at MyNameSpace.TimeServiceContextInitializer.Seed(TimeServiceContext db) in C:\Users\Justin\Source Control\CoutoTimeService\Console\Program.cs:line 51
at System.Data.Entity.DropCreateDatabaseIfModelChanges1.InitializeDatabase(TContext context)
at System.Data.Entity.Database.<>c__DisplayClass2
1.b_0(DbContext c)
at System.Data.Entity.Internal.InternalContext.<>c
_DisplayClass5.b_3()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.b
_4(InternalContext c)
at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
InnerException:

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T14:48:03+00:00Added an answer on May 23, 2026 at 2:48 pm

    add a constructor to your project class

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

    you can also make your code a bit pretier with object initializers like this:

    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
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm having trouble mapping two entities together with Entity Framework CTP5 using Code First
I'm using EF4 CTP5 code first approach but am having trouble getting it to
I first got an error usign the code below, explaining that DataGridLinkButton' must be
I'm having trouble reading a compressed (deflated) data file using C# .NET DeflateStream(..., CompressionMode.Decompress)
First off, I'm using Access 2000 and DAO. I have code that executes a
I am very new To EntityFramework and having trouble to understand why first code
A bit of background first: I am using base code from a remote SVN
I'm using code that I found on the CodeProject.com for a low-level keyboard hook
I'm using code that takes a bitmap and converts it to 24 BPP so
Using the code below, I am returning an nvarchar field from MS SQL 2005

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.