Entity Framework: View exclusion without primary key

时光总嘲笑我的痴心妄想 提交于 2019-12-13 06:02:41

问题


I am using SQL Server where I have designed a view to sum the results of two tables and I want the output to be a single table with the results. My query simplified is something like:

SELECT SUM(col1), col2, col3
FROM Table1
GROUP BY col2, col3

This gives me the data I want, but when updating my EDM the view is excluded because "a primary key cannot be inferred".

With a little research I modified the query to spoof an id column to as follows:

SELECT ROW_NUMBER() OVER (ORDER BY col2) AS 'ID', SUM(col1), col2, col3
FROM Table1
GROUP BY col2, col3

This kind of query gives me a nice increasing set of ids. However, when I attempt to update my model it still excludes my view because it cannot infer a primary key. How can we use views that aggregate records and connect them with Linq-to-Entities?


回答1:


As already discussed in the comments you can try adding MAX(id) as id to the view. Based on your feedback this would become:

SELECT ISNULL(MAX(id), 0) as ID, 
       SUM(col1), 
       col2, 
       col3 
FROM   Table1 
GROUP BY col2, col3

Another option is to try creating an index on the view:

CREATE UNIQUE CLUSTERED INDEX idx_view1 ON dbo.View1(id)



回答2:


I use this code alter view

ISNULL(ROW_NUMBER() OVER(ORDER BY ActionDate DESC), -1) AS RowID 

I use this clause in multi relations view / table query

ROW_NUMBER never give null value because it never seen -1



来源:https://stackoverflow.com/questions/17176014/entity-framework-view-exclusion-without-primary-key

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