Entity Framework v.1 中的外键关系

发布于 2024-09-05 20:08:42 字数 606 浏览 3 评论 0原文

我需要在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

比忠 2024-09-12 20:08:42

只需将代码更改为:

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"; 
    } 
} 

注意 Include(...),它告诉 EF 急切地加载每个用户的访问。

有了这个就应该可以工作了。

实际上,如果网页也是导航,您可能需要:

Include("Visits.Webpage");

希望这有效

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文