gpt4 book ai didi

entity-framework-4.1 - EF 4.1 Code First 数据库初始化 System.NullReferenceException 加载数据

转载 作者:行者123 更新时间:2023-12-04 08:21:08 25 4
gpt4 key购买 nike

我正在使用 EF 4.1 Code First,但我无法按照我认为应该能够的方式初始化我的数据。在下面的代码中,您将看到我有一个以 Client 开头的模型,它包含一系列相关的对象。我加载每个对象类型并将其设置为它的父对象。在我的数据加载到我的对象中后,我尝试将顶级对象 Client 保存到数据库中。当我这样做时,我得到一个 System.NullReferenceException。

EF不会做深度加载吗?

我是否需要先将每个对象集保存到数据库中,然后将它们相互关联,然后再将它们保存到数据库中?如果我必须这样做,当它应该能够在一个查询中执行时,加载我的数据似乎会有很多连接。

任何建议或答案将不胜感激。

下面是我的代码,下面是我的异常(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; }
}
}

逃避细节:
System.NullReferenceException 未被用户代码处理
Message=对象引用未设置为对象的实例。
源=控制台
堆栈跟踪:
在 C:\Users\Justin\Source Control\CoutoTimeService\Console\Program.cs:line 51 中的 MyNameSpace.TimeServiceContextInitializer.Seed(TimeServiceContext db)
在 System.Data.Entity.DropCreateDatabaseIfModelChanges 1.InitializeDatabase(TContext context)
at System.Data.Entity.Database.<>c__DisplayClass2
1.b_0(数据库上下文 c)
在 System.Data.Entity.Internal.InternalContext.<>c_DisplayClass5.b_3()
在 System.Data.Entity.Internal.InternalContext.PerformInitializationAction( Action Action )
在 System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
在 System.Data.Entity.Internal.LazyInternalContext.b_4(InternalContext c)
在 System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput 输入)
内部异常:

最佳答案

将构造函数添加到您的项目类

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

关于entity-framework-4.1 - EF 4.1 Code First 数据库初始化 System.NullReferenceException 加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6620141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com