thiag0
thiag0

Reputation: 2229

LINQ - Select Statement - The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type

I am trying to achieve the following...

 _4S.NJB_Request request =
                (from r in db.NJB_Requests
                 where r.RequestId == referenceId
                 select r).Take(1).SingleOrDefault();

Getting the following exception...

    Message:
The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.


StackTrace:
   at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)
   at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries)
   at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
   at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression)
   at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
   at DAL.SqlDataProvider.MarkNJBPCRequestAsComplete(Int32 referenceId, Int32 processState)

I have verified that 'referenceId' does have a value.

Anyone know why this would happen in a select statement?

Thanks!

EDIT: r.RequestId = NOT NULL Int, referenceId = int

Upvotes: 0

Views: 1923

Answers (2)

Oskar Kjellin
Oskar Kjellin

Reputation: 21900

Is r.RequestId nullable? Then you would use:

 _4S.NJB_Request request =
                (from r in db.NJB_Requests
                 where r.RequestId == (int?)referenceId
                 select r).FirstOrDefault();

Are your dc up to date with the database? Perhaps you have a null in the database that is being assigned to an int becuase your model is not synced with the database

Upvotes: 1

heisenberg
heisenberg

Reputation: 9759

I think the Take call is redundant and keeping the SingleOrDefault from saving you from the exception, try replacing Take(1).SingleOrDefault with FirstOrDefault:

(from r in db.NJB_Requests
                 where r.RequestId == referenceId
                 select r).FirstOrDefault();

edit: changed SingleOrDefault to FirstOrDefault to avoid getting an exception if more than 1 item is returned.

Upvotes: 0

Related Questions