Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add a primary key to a sql view? - Or alternate way to link views to LINQ-2-Entities

I'm adding a very simple view (or trying to) to my entities object model. The database is in SQL Server 2008. I'm on .Net 3.5 (SP1) using C#.

The view has two fields: color and colorcount, a Varchar(50) and a count(*) respectively.

When I do Update Model from Database, and select the view to add, it runs (it updated tables, adding fields no problem) but does not add the view. No error, warnings, or messages are displayed.

When I open the .edmx file I see that it shows Warning 6013: No primary key defined.

The view is complex and I would rather not translate it to a LINQ query. How can I add a primary key so that Entities will support the view?

Is there a non-hack-around way to add a view like this to an EDMX?

like image 475
Russell Steen Avatar asked Nov 30 '09 19:11

Russell Steen


People also ask

Can you add a primary key to a view?

You cannot create a primary key on a view.

How do you select primary key in SQL?

Right-click the row selector for the column and select Set Primary Key.

How do I add a key to a database?

Create a primary key to associate data between multiple tables. In the Navigation Pane, right click a table, and select Design View. Select the field or fields you want to use as the primary key.

Can we create primary key on view in MySQL?

A views can't create primary key. Normally using "SELECT" command to do.In my opinion if you need to insert you have to create new table and using FOREIGN KEY to REFERENCE and It can using INDEXED. While it is possible to create indexes on views in some databases, MySQL does not support indexes on views.


1 Answers

After you create the view using schemabinding you can add a primary key to it:

CREATE VIEW Colors WITH SCHEMABINDING
AS SELECT Color='yellow', ColorCount=100
GO
CREATE UNIQUE CLUSTERED INDEX PK_Colors ON Colors (Color)
like image 96
Pent Ploompuu Avatar answered Sep 25 '22 00:09

Pent Ploompuu