Foreign key relationships in Entity Framework v.1
I need to be to create an entity data model in the EF version 1, because my web host doesn't have Framework 4.0 yet. Below is just a simple example to show the problem.
I have 3 tables, one Users table, another Webpages table, and one table with Visits. The former two tables each have a one-to-many relationship with the Visits table (which basically works as a many-to-many relationship, only the Visits table has its own primary key and extra fields)
With the 4.0 version this works, but it doesn't with v.1. "Visits" has a count of 0, so the test string returns ""... Why, and how would I be able to access the foreign key relation in v.1?
UsersEntities context = new UsersEntities();
var users = context.Users;
string result = "";
f开发者_运维百科oreach (var user in users)
{
foreach (var visit in user.Visits)
{
result += visit.Webpage.Url + "\n";
}
}
So the foreach loop loops through the users, which it gets ok, but the inner loop is never entered because there are no Visits returned. Again, in Framework 4.0 it works fine, using the same database.
So what's wrong?
Simply change your code to this:
UsersEntities context = new UsersEntities();
var users = context.Users.Include("Visits");
string result = "";
foreach (var user in users)
{
foreach (var visit in user.Visits)
{
result += visit.Webpage.Url + "\n";
}
}
Notice the Include(...) that tells EF to eagerly load each User's visits.
With that in place it should work.
Actually if Webpage is a navigation too, you might need:
Include("Visits.Webpage");
Hope this works
精彩评论