All our CRUD operations have a CommitTransaction()
at the end before returning the results of a Method. For instance, we have a method Create()
that creates a record if there is no existing record with a Status: 'Float'
. Otherwise, it selects the record and updates its contents.
This is working as checked in the Database. The problem is, the method is returning its previous data and not the updated one:
public class Sample
{
public int ID {get; set;}
public string Code {get;set;}
public decimal Total {get; set;}
}
In Create()
, Code
and Total
is entered by the user which should update the data in the database.
E.g.
ID | Code | Total
1 | CodeName | 100
The user updates
Code : 'Code1'
Total : 200
But the Method still returns
Code : 'CodeName '
Total : 100
But if checked in the Database, it is already
ID | Code | Total
1 | Code1 | 200
I have observed that this only happens when a CommitTransaction()
is used which is not advisable to remove but a correct data return is also needed.
Here is a simplified replica of Create()
:
private string procCRUD = "procCreate @ID={0},@Code={1},@Total={2}";
public Sample Create(Sample data)
{
IQueryable<ComponentType> query = contextBase.Samples.FromSql(procCRUD,"create",data.ID, data.Code, data.Total); // contextBase.Samples is the DbContext
commit(); // this commits the transaction
return query;
}
procCRUD is a stored procedure:
DROP PROCEDURE IF EXISTS procCreate
GO
CREATE PROCEDURE procCreate
@proc varchar(20) = 'create',
@ID bigint = 0,
@Code varchar(20)= NULL,
@Total int= 0
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SQL varchar(MAX)
SET @SQL = ''
IF (@proc='create') BEGIN
IF (NOT EXISTS(SELECT ID FROM Sample WHERE Status='Float'))
BEGIN
INSERT INTO Sample(Code, Total) VALUES( @Code, @Total)
SET @ID = @@IDENTITY;
END
ELSE
BEGIN
SELECT @ID=ID FROM Sample WHERE Status='Float'
UPDATE Sample SET
Code = @Code
,Total = @Total
WHERE ID=@ID
END
END
SET @SQL = 'SELECT TOP 1 * FROM Sample '
EXEC SP_EXECUTESQL @SQL
END
GO
I have tried manually setting the return value e.g. query.Code = data.Code
before the return but it is time-consuming if I have more than 10 Class properties. Also, some properties are not entered by the user but retrieved from the database depends on another property entered.
I wonder if some of you also encountered this problem. Any help will be appreciated. Thank you.
(edited)