Can SQL Server views have primary and foreign keys?

≯℡__Kan透↙ 提交于 2019-11-30 13:02:19

You need to define your view so that it:

  • Includes all the PRIMARY KEY columns
  • Does not use any JOIN's
  • Does not use any aggregate functions or UNION's

Any row from your view should map to exactly one row from the table.

One of my problem views uses aggregate functions

It cannot be updateable. For a readonly entity, a solution from here:

When no key can be inferred, a code comment that contains the corresponding EntityType element (with no Key elements) is added to the SSDL section of the .edmx file.

In your case, since it seems that you want a read only entity, you could:

  1. uncomment the SSDL entity
    • mark one/some properties as Nullable="False"
    • add the appropriate Key elements
    • add a corresponding defining query.

For the second question:

The other ought to have a compound primary key of two foreign keys

From documentation:

A table that represents a many-to-many relationship between two tables in the database may not have an equivalent entity in the conceptual schema. When the EDM tools encounter such a table with no columns other than the two that are foreign keys, the mapping table is represented in the conceptual schema as a many-to-many association instead of an entity.

live-love

You can alter your views by creating a NOT NULL index column in your view doing something like this:

ALTER VIEW [dbo].[ViewName]
AS
    SELECT  ISNULL(CAST(CASE ROW_NUMBER() OVER ( ORDER BY columnNames )
                          WHEN ROW_NUMBER() OVER ( ORDER BY columnNames )
                          THEN ROW_NUMBER() OVER ( ORDER BY columnNames )
                          ELSE 0
                        END AS INT), 0) AS ID 

Actually, you can create a view that uses JOIN's and generate and Entity in your model from it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!