I am trying to grasp EF Code First but I still do not get how to access the referenced objects from another class (due to lack of enough knowledge, I cannot even formulate the question).
Here's what my simple code looks like:
public class Destination
{
public int DestinationId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Description { get; set; }
public byte[] Photo { get; set; }
public List<Lodging> Lodgings { get; set; }
}
public class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public bool IsResort { get; set; }
public Destination Destination { get; set; }
}
public class BreakAwayContext: DbContext
{
public DbSet<Destination> Destinations { get; set; }
public DbSet<Lodging> Lodgings { get; set; }
}
private static void InsertDestination()
{
var destination = new Destination
{
Country = "Indonesia",
Description = "EcoTourism at its best in exquisite Bali",
Name = "Bali"
};
using(var context = new BreakAwayContext())
{
context.Destinations.Add(destination);
context.SaveChanges();
}
}
private static void InsertLodging()
{
var lodging = new Lodging()
{
Name = "x",
IsResort = false,
Owner = "asdasd"
};
using(var context = new BreakAwayContext())
{
var dest = context.Destinations.Find(1);
lodging.Destination = dest;
context.Lodgings.Add(lodging);
context.SaveChanges();
}
}
private static void ShowLodgings()
{
using(var context = new BreakAwayContext())
{
foreach(var l in context.Lodgings)
{
Console.WriteLine("{0} {1} {2}", l.Name, l.Owner, l.Destination.Name);
}
}
}
I get a NullReferenceException on the line I try to write the destination name to the console.
Thanks in advance.
Try using
navigation properties
:First make
Destination
virtualThen use
Include
methodJust set
Destination
property in yourLodging
class,virtual
. This tell, the EF to loadDestination
automatically when you need it(Lazy Loading). So yourLodging
class should looks like: