I have the following two models
[DataContract]
public class Event
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public Place Place { get; set; }
}
[DataContract]
public class Place
{
[Key]
public string ID { get; set; }
public string Name { get; set; }
}
and data context class:
public class myDB: DbContext
{
public DbSet<Event> Events { get; set; }
public DbSet<Place> Places { get; set; }
}
I run the following code for example
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Foo();
}
private void Foo()
{
var db = new myDB();
var place = new Place
{
ID = "{59E0F90C-03DB-453C-8C9E-4747957ED37E}",
Name = "Home",
};
db.Places.Add(place);
db.SaveChanges();
var @event = new Event
{
Name = "Test",
Place = place,
TimeFrame = new TimeFrame() {StartTime = DateTime.Now, EndTime = DateTime.Now }
};
db.Events.Add(@event);
db.SaveChanges();
var eventIndex = @event.ID;
var ev = db.Events.Find(@eventIndex);
var evPlace = ev.Place;
var pl = db.Places.Find("{59E0F90C-03DB-453C-8C9E-4747957ED37E}");
}
everything works fine and evPlace is the object I just added to db, pl is also not null.
But when I try to run the following code from the controller where 5 is the ID of the new event object
var ev = _db.Events.Find(5);
var evPlace = ev.Place;
var pl = _db.Places.Find("{59E0F90C-03DB-453C-8C9E-4747957ED37E}");
pl and ev are not null but ev.Place is null (evPlace)
Any idea why?
The problem has nothing to do with the primary key being a
stringor not. Generally Entity Framework doesn’t load navigation properties automatically. You need to specify that explicitly:Or: If you declare the
Placeproperty asvirtual……EF will enable lazy loading for this property and load the
Placefrom the database as soon as you access it in your code. Your code example would work then. Be aware that lazy loading leads to a second query/roundtrip to the database whereas eager loading (Include) loads both the event and the place in a single query.More about loading related entities is here.