I have the following code:
public void Crear(UsuarioDto registro) {
VisitantesEntities db = new VisitantesEntities();
registro.Id = Convert.ToInt32(db.SpUsuarioMaxId());
db.SpCrearUsuario(registro.Id, registro.Nombre, registro.Correo, registro.CodigoAcceso, registro.ClaveAcceso, registro.UsuarioId, registro.RolId);
db.SaveChanges();
}
On receipt the record object to store its values in the database using the store procedure SpCrearUsuario
. However, first I must find the Id of the last user, for which I use the store procedure SpUsuarioMaxId
, but when trying to convert the result of this store procedure to Int
be able to assign the value to registro.Id
it shows me the following error:
System.InvalidCastException: 'Unable to cast object of type 'System.Data.Entity.Core.Objects.ObjectResult`1[System.Nullable`1[System.Int32]]' to type 'System.IConvertible'.'
Is it possible to convert the result of an object to an integer?
The code of the Store Procedure is this:
USE [Visitantes]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SpUsuarioMaxId]
AS
BEGIN
SELECT MAX(Id) AS MaxId
FROM Usuario
END;
As @Japh Sxas mentions in his comment, the type
ObjectResult<T>
implementsIEnumerable<T>
, so it is likely that your procedure will return more than one element, to get the value you want (if only one record will exist as a product of that query) , you can do:Method number 1:
Change this line:
By:
To make use of the function
FirstOrDefault()
you must dousing System.Linq;
at the beginning of the file.Method number 2 (Not tested) :
I haven't tried this method, but it should work. Change your stored procedure definition to:
With that modification, your stored procedure should be able to directly return the value as an integer, after making that modification, you must update your Entity Framework model so that the return type changes.
Cheers,
Try modifying this, it seems that the return value is
null
.To avoid the problem, use
ISNULL
but remember that you must add one to the id you get to generate the following
I would also recommend evalues if that id cannot be defined as
IDENTITY
in the db table, that is, autonumerical, so it is automatically increased when performing the insert