Hello.
I use custom sql-insert statement that calls stored procedure.
Code:
<class name="AST.PartnerSite20.Core.Domain.User, AST.PartnerSite20.Core.Dao">
<id name="UserId" type="System.Int32" column="UserId" unsaved-value="0">
<generator class="assigned"/>
</id>
<property name="ClientId" type="System.Int32" not-null="true" />
.......
<sql-insert check="none">
exec up_User_i @ClientId=?, @Login=?, @FirstName=?, @LastName=?, @Email=?, @Password=?, @UserId=?
</sql-insert>
And my stored proc looks like:
Code:
PROCEDURE [dbo].[up_User_i]
(
@UserId INT =NULL OUT,
@ClientId INT,
@Login VARCHAR(50),
@FirstName VARCHAR(50),
@LastName VARCHAR(50),
@Email VARCHAR(50),
@Password VARCHAR(50)
)
AS
BEGIN
DECLARE @ResultCode INT
-- Check if user with the same login exists
IF EXISTS(SELECT * FROM dbo.vw_Users WHERE Login=@Login)
SET @ResultCode = -1;
ELSE BEGIN
DECLARE @PrincipalId INT
INSERT INTO dbo.tblUserPrincipals (ClientId, Type)
VALUES(@ClientId, 'U')
SET @PrincipalId = SCOPE_IDENTITY()
INSERT INTO dbo.tblUsers (UserId, Login, FirstName, LastName, Email,Created,Password, ExpirePassword)
VALUES (@PrincipalId, @Login, @FirstName, @LastName, @Email, GETDATE(),@Password, getdate())
SET @ResultCode = @PrincipalId
SET @UserId = @PrincipalId
END
SELECT @ResultCode AS ResultCode
END
As you can see Users primary key generated by stored procedure.
What should I do to obtain primary key, generated by stored proc or which approach is more preferable for me.
Also I tried to create custom generator (see bellow), but SCOPE_IDENTITY() doesn't work after procedure call and it's behavior is unpredictable.
Code:
public class StoredProcGenerator : IIdentifierGenerator
{
private const string sql = "SELECT SCOPE_IDENTITY()";
#region IIdentifierGenerator Members
[MethodImpl(MethodImplOptions.Synchronized)]
public object Generate(ISessionImplementor session, object obj)
{
IDbConnection conn = session.Factory.OpenConnection();
IDbCommand qps = conn.CreateCommand();
qps.CommandText = sql;
qps.CommandType = CommandType.Text;
try
{
IDataReader rs = qps.ExecuteReader();
if (rs.Read())
{
if (!rs.IsDBNull(0))
{
return rs.GetValue(0);
}
else
{
throw new IdentifierGenerationException(
string.Format(CultureInfo.CurrentCulture,
"Identifier generation failed: Sql query '{0}' have returned an identity with NULL value",
sql));
}
}
else
{
throw new IdentifierGenerationException(
string.Format(CultureInfo.CurrentCulture,
"Identifier generation failed: Sql query '{0}' have returned 0 records", sql));
}
}
finally
{
session.Factory.CloseConnection(conn);
}
}
#endregion
}
Thanks.