The foreign key is obtained through the entity framework.

c# entity-framework linq

Question

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?

1
1
12/27/2011 7:44:38 PM

Accepted Answer

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;
1
5/23/2017 12:20:13 PM

Popular Answer

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:

enter image description here

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow