Every time I am trying to get a related object I get error
Object reference not set to an instance of an object
Relevant code:
public class Project
{
public int ProjectId { get; set; }
public string ProjName { get; set; }
public string Description { get; set; }
public virtual List<Developer> MyDevs { get; set; }
}
public class Developer
{
public string Name { get; set; }
public string Skills { get; set; }
public string Email { get; set; }
public virtual Project MyProj { get; set; }
}
//define relationship using fluent api, under AppDbContext
modelBuilder.Entity<Developer>()
.HasOne(d => d.MyProj)
.WithMany(p => p.MyDevs)
.HasForeignKey("ProjectForeignKey");
Add-migration and update-database give no error, but I am not able to find the myDev column in the Project table. I am not able to find the myProj column in the Developer table either, only the foreignkey column.
Running the following seed method adds one project and one developer to the db as expected.
public static void Seed(IApplicationBuilder applicationBuilder)
{
AppDbContext context = applicationBuilder.ApplicationServices.GetRequiredService<AppDbContext>();
Project ProjA = new Project { ProjName = "handyApp", Description = "a dummy Project" };
context.Project.Add(projA);
Developer FirstDev = new Developer { UserName = "John Smith", Skills = "C#", Email = "jsmith@dummymail.com", MyProj = ProjA};
context.Developer.Add(FirstDev);
context.SaveChanges();
}
Then running the following code hits the "Object reference not set to an instance of an object" exception.
Developer Dev = context.Devs.Find(1);
string name = Dev.MyProj.ProjName; //put a break point here, the dubugger tells me Dev.MyProj is null
Please can anyone help to identify what is wrong with my relationship definition.