Linq to EF 不选择外键
所以我有两个表,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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来延迟加载由于某种原因被关闭,所以尝试
Include
- 这应该有效:您正在使用什么 EF 版本?是代码优先还是数据库优先?
此外,当您通过导航属性访问相关实体时,您不使用 FK - 您应该能够访问 objs.Table2.Id ,前提是
Id
是主键Table2
实体。编辑:
听起来您没有勾选在模型中包含外键 - 请务必添加它。如果右键单击模型并选择“从数据库更新模型...”,您将看到以下对话框。
It looks like lazy loading is turned off for some reason, so try
Include
- this should work: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
providedId
is the primary key of theTable2
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.