Linq to EF 不选择外键

发布于 2024-10-28 04:38:42 字数 409 浏览 1 评论 0原文

所以我有两个表,Table1 和 Table2。表 1 有一个整数,它是表 2 的标识列的外键,我将其称为 FK Table2ID。如果我执行此查询:

var objs = (from t in DataContext.Table1 select t).Single();

objs.Table2.Table2ID 为空。但是,我可以使用如下查询轻松选择值:

var Table2ID = (from t in DataContext.Table1.Table2.Table2ID).Single();

How can I select back the value of the FK in Table1 using the 第一个查询,以及为什么它不自动返回?

So I have two tables, Table1 and Table2. Table one has an integer that is a foreign key to the identity column of Table2, I will call this FK Table2ID. If I perform this query:

var objs = (from t in DataContext.Table1 select t).Single();

objs.Table2.Table2ID is null. However I can easily select the value using a query like this:

var Table2ID = (from t in DataContext.Table1.Table2.Table2ID).Single();

How can I select back the value of the FK in Table1 using the first query, and why is it not returning automatically?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

泅人 2024-11-04 04:38:42

看起来延迟加载由于某种原因被关闭,所以尝试 Include - 这应该有效:

var objs = (from t in DataContext.Table1.Include("Table2") select t).Single();

您正在使用什么 EF 版本?是代码优先还是数据库优先?

此外,当您通过导航属性访问相关实体时,您不使用 FK - 您应该能够访问 objs.Table2.Id ,前提是 Id 是主键Table2 实体。

编辑:

听起来您没有勾选在模型中包含外键 - 请务必添加它。如果右键单击模型并选择“从数据库更新模型...”,您将看到以下对话框。

在此处输入图像描述

It looks like lazy loading is turned off for some reason, so try Include - this should work:

var objs = (from t in DataContext.Table1.Include("Table2") select t).Single();

What EF version are you working with ? Is this code first or database first?

Also when you are accessing related entities through a navigation property you do not use the FK - you should be able to access objs.Table2.Id provided Id is the primary key of the Table2 entity.

Edit:

It sounds like you didn't tick off to include foreign keys in your model - make sure to add it. If you right click your model and select "Update model from database..." you will get the following dialog.

enter image description here

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