I have this stored procedure, which is mapped in an Entity Framework 4.1 object. The call is made within the
using (TransactionScope transaction = new TransactionScope())
{
try
{
DbEntity.Car.AddObject(CarInfo);
DbEntity.SaveChanges();
/* Other object savings */
transaction.Complete();
DbEntity.AcceptAllChanges();
}
catch (Exception exp)
{
throw exp;
}
finally
{
DbEntity.Dispose();
}
}
I see the stored procedure mapping done currently. If I execute the stored procedure alone on MS SQL server, it executes it correctly.
Here is the stored procedure
ALTER PROCEDURE [dbo].[Carinsert] @Qty INT
,@StyleID INT
,@TFee MONEY
,@HWayTax MONEY
,@OFees MONEY
,@OFeesDescription NTEXT
,@MUp DECIMAL(18, 4)
,@BAss MONEY
,@PriceMSRP MONEY
,@PriceSpecial MONEY
AS
BEGIN
SET nocount ON
DECLARE @PTotal MONEY
DECLARE @TaxFeesNet MONEY
DECLARE @CarID INT
SET @TaxFeesNet = Isnull(@TFee, 0) + Isnull(@HWayTax, 0)
+ Isnull(@OFees, 0)
IF( @PriceSpecial IS NULL )
BEGIN
SET @PTotal = @PriceMSRP + @TaxFeesNet
END
ELSE
BEGIN
SET @PTotal = @PriceSpecial + @TaxFeesNet
END
INSERT INTO Car
(Qty
,StyleID
,MUp
,BAss
,PriceMSRP
,PriceSpecial
,TFee
,HWayTax
,OFees
,OFeesDescription
,PriceTotal)
VALUES (@Qty
,@StyleID
,@MUp
,@BAss
,@PriceMSRP
,@PriceSpecial
,@TFee
,@HWayTax
,@OFees
,@OFeesDescription
,@PTotal)
SELECT Scope_identity() AS CarID
END
If I execute this like on MS SQL it calculates the PriceTotal column in the table as 3444.00, which is correct.
@Qty= 5,
@StyleID = 331410,
@TFee = NULL,
@HWayTax = NULL,
@OFees = NULL,
@OFeesDescription = NULL,
@MUp = 4,
@BAss = 10000,
@PriceMSRP = 20120,
@PriceSpecial = 3444
When I run the MVC web application, and I debug & see these are the values passed and the PriceTotal comes to 20120.00
I couldn’t figure out why it does not do the IF ELSE calculation & use the price.
Does anybody else see something weird? This has been daunting for few days now. Any help appreciated. Thanks
Update
I updated the title to better guide others
After few minutes of posting the question, I figured it all out.
There was actually 2 bug.
Entity framework used the UPDATE stored procedure even when I try to INSERT new records. Just for records, the UPDATE stored procedure required the CarID [primary key]. May be EF first does the INSERT and then does the UPDATE right away, even for creating new records?
The UPDATE sproc had a bug checking for NULL using <>. It should have been IS NOT NULL
In anycase, now This is a bigger issue. How to force EF to use INSERT sproc and not the UPDATE when I only want to do is create a new record?
I tried
DbEntityContext.ObjectStateManager.ChangeObjectState(carInfo, EntityState.Added);
and still EF kept on calling the UPDATE sproc.