c# - Linq 到实体 (EF) : How to get the value of a FK without doing the join

标签 c# asp.net entity-framework

我正在使用 Linq to Entities。我的主表 Employee setup 有一个名为 vendorID 的字段。供应商 ID 是供应商表的外键。

就目前而言,Employee 对象不直接公开 vendorID。相反,我只能通过这种方式访问​​它:

var employee = (from e in context.Employees.Include("tbl_vendors")
               where e.employeeID = 1
               select e).FirstOrDefault();

//this gets the vendor ID
int vendorID = employee.tbl_vendors.vendorID;

这很好,很花哨,但它是对数据库的额外工作,因为它强制在不需要的地方进行连接。有没有办法在不被迫连接到 tbl_vendors 表的情况下获取该键值?

最佳答案

其实这很简单,你基本上是这样做的:

var tblVendorID = (from e in context.Employees
                  select e.tbl_vendors.ID).FirstOrDefault();

即使这看起来像您正在执行联接,L2E 也会优化联接。

您可以使用如下代码确认:

var results = from e in ctx.Employees
              select e.tbl_vendors.ID;

var query = results as ObjectQuery<int>;
string sql = query.ToTraceString();

希望对你有帮助 亚历克斯(微软)。

关于c# - Linq 到实体 (EF) : How to get the value of a FK without doing the join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/779193/

相关文章:

ASP.NET MVC 3 : Model comes empty in the controller?

c# - 捕捉 COM 事件?

c# - 偶尔出现SqlException : "XML parsing: illegal xml character" happens when website submitting form

html - 如何为普通用户禁用或删除 DNN 中的 default.css、skin.css 和 portal.css

c# - 如何使用 Entity Framework 自动包含所有底层导航属性

c# - 从 View 模型保存到 ASP.NET MVC 中的模型

c# - 递归linq查询

c# - 如何在 C# 中禁用 MS Outlook 的安全弹出窗口?

c# - 在 C# 窗口中嵌入网页

asp.net - 如何检测 ASP.net 应用程序中的 SqlServer 连接泄漏?