简体   繁体   中英

Entity framework get the foreign key

I have 1:n relationship between to tables in a database: Employee (1) : Role (n) Role has foreignKey named idEmployee

I want to create a linq statement which will get every role for a given customer. I want to make something like this:

var myQuery = from r in Role 
              where r.idEmployee == someId
              select r;

But, r doesn't have an idEmployee property! How can I get the value of the foreign key?

If you're using EF 4.0 (.NET 4.0), and a database-first programming model with an EDMX model (visual designer), then you need to make sure to have the option Include foreign key columns in the model checked when you add tables to your EDMX model:

在此输入图像描述

If you don't have this option checked, then EF 4.0 will behave the same as EF 1.0/3.5 (in .NET 3.5) which is to include a navigation property - but not the foreign key column as a separate column.

If you are using EF4.0 at least, this will give you what you need: Foreign keys in Entity Framework

If you're using EF1.0 , your problem is more serious since it does not show foreign keys in model. You need to iterate through EntityKey.EntityKeyValues collection in search of valid value. But I think this would only get you value of foreign key and would not work in query (since EF would not know how to translate it to SQL query).

But since you have foreign keys, why don't you simply use NavigationProperty to navigate to Employee entity and check value there?

var myQuery = from r in Role 
              where r.Employee.idEmployee == someId
              select r;

Use the include method on Employee class to bring back all the related roles:

var myQuery = from e in Employees.Include(emp => emp.Roles)
              where e.EmployeeId == someId
              select e

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM