Vivian River
Vivian River

Reputation: 32400

Use Foreign Key on SQL View in Entity Framework

I'm relatively new to Entity Framework.

I created a database with two tables: Accounts and Assignments.

Accounts has an AccountId primary key which is used as a foreign key in the Properties table. I really like that the Entity Framework automatically picks up the foreign key relationship and allows me to access rows in Assignments as a property of each row from Accounts.

I went ahead and created a new View object that returns all the columns from Accounts along with some other information. However, when I get the data from the View in SQL using the Entity Framework, it is no longer automagically referencing the associated rows in the Assignments table.

How can I get the desired behavior using Views with Entity Framework

Upvotes: 4

Views: 9087

Answers (2)

Philip Johnson
Philip Johnson

Reputation: 1081

The solution that worked for me was to include the appropriate data in the view so I didn't need to use the FK.

For example, include the PK's for the Assignment table in the view by adding the appropriate SQL to the view.

That way I could join to the view in LINQ without needing to refer to a generated property in the EDMX.

Upvotes: 0

Craig Stuntz
Craig Stuntz

Reputation: 126587

This can work in EF, but the EF designer can't infer your FK out of the view, since the DB doesn't tell it where the FKs on view columns are (since they're naturally on the underlying tables, not the view itself).

You'll need to manually edit your EDMX, either via the designer or in XML, to get these properties.

Upvotes: 5

Related Questions