Entity Framework v.1 中的外键关系
我需要在 EF 版本 1 中创建实体数据模型,因为我的 Web 主机还没有 Framework 4.0。下面只是一个简单的例子来说明问题。
我有 3 个表,一个用户表,另一个网页表和一个访问表。前两个表均与 Visits 表具有一对多关系(基本上是多对多关系,只有 Visits 表有自己的主键和额外字段)
在 4.0 版本中,此功能有效,但 v.1 则不然。 “Visits”的计数为 0,因此测试字符串返回“”...为什么以及如何访问 v.1 中的外键关系?
UsersEntities context = new UsersEntities();
var users = context.Users;
string result = "";
foreach (var user in users)
{
foreach (var visit in user.Visits)
{
result += visit.Webpage.Url + "\n";
}
}
因此,foreach 循环遍历用户,这一切正常,但永远不会进入内部循环,因为没有返回访问。同样,在 Framework 4.0 中它使用相同的数据库工作正常。
那么出了什么问题呢?
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 = "";
foreach (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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需将代码更改为:
注意 Include(...),它告诉 EF 急切地加载每个用户的访问。
有了这个就应该可以工作了。
实际上,如果网页也是导航,您可能需要:
希望这有效
Simply change your code to this:
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:
Hope this works