Pregunta

I am working with DotNetNuke 7's DAL2 as outlined by Charles Nurse in his blog http://www.charlesnurse.com/Blog/tabid/226/EntryId/69/DAL-2-DataContext-Deep-Dive.aspx and have come across an unexpected error when using ExecuteScalar.

My stored procedure fires and inserts to the database but overall the code errors with a 'Invalid attempt to read when no data is present.'. I have seen this error related to the data Reader though in my case I use DotNetNuke's integration of PetaPoco. any insight its greatly appreciated. Here is the code

public int AddLocation(string LocationType, string Name, string Description, string Address, string AreaCode, string Telephone, int Capacity, float Long, float Lat)
        {
            int id;
            using (IDataContext db = DataContext.Instance())
            {

                id = db.ExecuteScalar<int>(CommandType.StoredProcedure,
                    "CP_AddLocation", LocationType, Name, Description, Address, AreaCode, Telephone, Capacity, Long, Lat);
            }
            return id;
        }

And my Stored Procedure. it works by itself and returns the newest Id. I should mention something I noticed and found odd is that if I declare a parameter as an output param ie @LocationId int OUTPUT then the addLocation() method does not work giving and error like this "Expected parameter @LocationId".

CREATE PROCEDURE [dbo].[CP_AddLocation]
 @locationType nvarchar(100),
 @name nvarchar(100),
 @description nvarchar(200),
 @address nvarchar(250),
 @areaCode nvarchar(50),
 @telephone nvarchar(50),
 @capacity int,
 @long float,
 @lat float

AS

DECLARE @geoCode geography
SET @geoCode = geography:: STGeomFromText('POINT (' + CAST(@long AS varchar) + ' ' + CAST(@lat AS varchar) + ')',4326);
BEGIN
INSERT INTO CP_Locations(
    LocationType,
    Name,
    Description,
    Address,
    AreaCode,
    Telephone,
    GeoCode,
    Capacity,
    Long,
    Lat)
    VALUES(
    @locationType,
    @name,
    @description,
    @address,
    @areaCode,
    @telephone,
    @geoCode,
    @capacity,
    @long,
    @lat)
END
declare @locationId int;
select @locationId = SCOPE_IDENTITY()
return @locationId;
¿Fue útil?

Solución

Execute scalar requires the value to be selected as it gets the value from the first row and first column of the result set.

So just replace your last 3 lines of your Stored Procedure with

SELECT SCOPE_IDENTITY()

And you will be set!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top