I've got a simple table with two fields that are updated via triggers.
CREATE TABLE [dbo].[CarType](
[idCarType] [int] IDENTITY(1,1) NOT NULL,
[CarTypeName] [nvarchar](50) NOT NULL,
[CR_Date] [datetime2](7) NOT NULL CONSTRAINT [DF_CarType_CR_Date] DEFAULT (getdate()),
[LU_Date] [datetime2](7) NOT NULL CONSTRAINT [DF_CarType_LU_Date] DEFAULT (getdate()),
CONSTRAINT [PK_CarType] PRIMARY KEY CLUSTERED ( [idCarType] ASC)
)
END
GO
EXEC dbo.sp_executesql @statement = N'
CREATE TRIGGER [dbo].[CarType_Insert] ON [dbo].[CarType]
AFTER INSERT AS
BEGIN
UPDATE dbo.CarType
SET dbo.CarType.CR_Date=getdate(), dbo.CarType.LU_Date=getdate()
FROM dbo.CarType
INNER JOIN Inserted ON dbo.CarType.idCarType = Inserted.idCarType
END'
GO
EXEC dbo.sp_executesql @statement = N'
CREATE TRIGGER [dbo].[CarType_Update] ON [dbo].[CarType]
AFTER UPDATE AS
BEGIN
UPDATE dbo.CarType
SET dbo.CarType.LU_Date=getdate()
FROM dbo.CarType
INNER JOIN Inserted ON dbo.CarType.idCarType = Inserted.idCarType
END'
GO
When I do an add new with:
CarEntities db = new CarEntities();
CarType car = new CarType()
{
CarTypeName = "Ford"
};
db.CarTypes.Add(carType);
db.SaveChanges();
carType.Dump(); //extension to print out type as JSON
CarType newCar = db.CarTypes.AsNoTracking().Where(e => e.idCarType == carType.idCarType).First();
newCar.Dump(); //extension to print out type as JSON
carType comes back as:
{
"idCarType": 8,
"CarTypeName": "Ford",
"CR_Date": "0001-01-01T00:00:00",
"LU_Date": "0001-01-01T00:00:00"
}
but newCar comes back as:
{
"idCarType": 8,
"CarTypeName": "Ford",
"CR_Date": "2014-12-18T07:53:27.773",
"LU_Date": "2014-12-18T07:53:27.773"
}
but only if I add the AsNoTracking
part.
Any idea how to get the updated fields with the ADD as opposed to forcing a database query?