Entity Framework and Primary Keys

Entity Framework relies on primary keys with views and tables.  If you are trying to bring a view into dbContext and the view does not have a primary key the following should help you out.  The schema object has to have primary key defined and it be set to not allow nulls (not-null).

The solution for me was to refashion my view definition using RowId like the following

This will create a non-null RowId for each row in the result.

SELECT ISNULL(ROW_NUMBER() OVER(ORDER BY P1), -1) AS RowID, P1 AS Code, P3, P2
FROM dbo.BigTable WHERE P1 IS NOT NULL

After you create the view take a look at the view definition within SQL Server Management Studio.  You should see that you have defined a column RowId which is non null.  This will satisfy Entity Framework and dbContext can now include a reference to these views or tables.

ef

Author

david

comments powered by Disqus

Categories

Recent Tweets

Retweeted by @dyardy Hey C# peeps, we’re trying C# in browser with reference content. Try it here: docs.microsoft.com/dotnet/csharp/… reply with feedback /cc @LadyNaggaga
23 Amazing Vintage Photographs Taken Inside WWII Tank Factories ~ vintage everyday vintag.es/2017/10/23-ama…
When is AI NOT Search? Artificiality intelligence==Search Engine (there cases when this is not true)
@projectedxyz Large data vs big data? Industry has so misused buzz words to sell products, and so you end up nothi… twitter.com/i/web/status/9…