LINQ到实体(EF):如何获得FK的值而不做加盟

问题描述:

我使用LINQ到实体。我有我的主表,员工设置一个叫VENDORID场。供应商ID是一个外键进入卖方表。

I'm using the Linq to Entities. I've got my main table, Employee setup with a field named vendorID. Vendor ID is a foreign key into the Vendors table.

由于它是现在,Employee对象不直接暴露VENDORID。相反,我只可以访问这种方式:

As it is right now, the Employee object does not directly expose the vendorID. Instead, I can only access it this way:

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表?

That is just fine and dandy, but it is extra work on the database because it is forcing a join where none is needed. Is there a way to get that key value without being forced to do a join to the tbl_vendors table?

您可以通过实体引用访问外键。

You can access the foreign key via the entity reference.

Employee employee = context.Employees.Single(e => e.employeeID == 1);

Int32 vendorID = (Int32)employee.tbl_vendorsReference.EntityKey.
   EntityKeyValues[0].Value;

请参阅MSDN上的的EntityReference 的EntityKey 类。

See MSDN for reference on the EntityReference and EntityKey classes.