Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a relationship between table and view in the Entity Framework

I have an Entity Framework model that was generated by the Visual Studio 2008 wizard based on a Sql Server 2008 database.

The model has a view that logically is joined in a many-to-many relationship with another table through a join table (enforced in the database by an insert/update trigger). Both tables and the view are part of the model, but because you cannot have a foreign key constraint on a view, it does not have the relationship between the view and the join table.

Is it possible to create a relationship in the Entity Framework model for this link between the join table and the view?

Thank you for any help.

like image 247
Sako73 Avatar asked Feb 02 '10 14:02

Sako73


People also ask

How will you create relationship between tables in Entity Framework?

You can create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table A and table B.

Can Entity Framework work with views?

Entity Framework : A Comprehensive Course Views can be used in a similar way as you can use tables. To use view as an entity, first you will need to add database views to EDM. After adding views to your model then you can work with it the same way as normal entities except for Create, Update, and Delete operations.

What are the possible ways of creating the relationship between the tables?

In an Access database, you create a table relationship using one of the following methods: In the Relationships window, add the tables that you want to relate, and then drag the field to relate them from one table to the other table. Drag a field on to a table datasheet from the Field List pane.


1 Answers

Yes, you can do this, but the GUI designer won't be able to infer it for you.

The first thing the need to do is configure the view correctly. The designer cannot infer the primary key, so you will need to supply that information.

You can now right-click in the empty space in the designer and then choose to add an association. Define the association between your view and table, setting the cardinality correctly.

In EF 1, you will need to remove the FK fields from the client schema by selecting them in the designer and pressing delete. This is because, in EF 1, you cannot have the same field mapped to both an association and in a scalar property. In EF 4, you can keep the FK fields if you use FK associations, or you can use independent associations which behave like EF 1.

like image 130
Craig Stuntz Avatar answered Oct 27 '22 13:10

Craig Stuntz