Database is throwing an InvalidOperationException status of 500 in a MVC Web Application while accessing data from an SQL View
-
21-12-2019 - |
Question
I am working on an Asp.Net MVC Application in which I have an SQL View with five columns and I have the following model for it
public class InferredBid
{
public int Id { get; set; }
public string Market { get; set; }
public string Term { get; set; }
public string Bid { get; set; }
public string Offer { get; set; }
}
SQL View
Create VIEW [dbo].[InferredBids]
AS
with numbered as
(
select id, product, grade, term, bid, offer, termid, row_number() OVER (Partition BY Product, Grade ORDER BY termid) i
from dbo.CanadianCrudes
)
select r1.i as Id, r1.product + '/' + r1.grade as Market, r1.term + '/' + r2.term as Term, r1.Bid - r2.Offer [Bid], r1.Offer - r2.Bid [Offer]
from numbered r1 join numbered r2 on r1.product = r2.product and r1.grade = r2.grade and r1.termid+1=r2.termid and r1.i<r2.i and r1.term!=r2.term
GO
When I open the page that should render the data from the above SQL view. It just threw me an InvalidOperationException
<m:type>System.InvalidOperationException</m:type>
<m:stacktrace/>
<m:internalexception>
<m:message>
The 'Id' property on 'InferredBid' could not be set to a 'Int64' value. You must set this property to a non-null value of type 'Int32'.
</m:message>
I tried setting the property to int32 but still I have the same issue.
Solution
Change your code to the following, as it appears that SQL is returning Int64 (equivalent to long
in C#) for that field.
public class InferredBid
{
public long Id { get; set; }
public string Market { get; set; }
public string Term { get; set; }
public string Bid { get; set; }
public string Offer { get; set; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow