我正在使用 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/