我在SQL Server表中定义了一个列,并使用After Insert Trigger设置其值。此值基于最近插入的标识计算。但是,在保存数据库更改后,我无法在Controller中获取此值。
这是我在控制器中的(伪)代码:
var model = new model();
model.column1 = abc;
model.column2 = xyz;
model.column3 = "CC";
// db object below is a model inheriting DbContext
db.table.Add(model);
db.SaveChanges();
// Do some operations not related to this table
// Try retrieving value of column3
// which should have been updated by the after insert trigger
var column3Value = db.table.find(model.id).column3;
我在这里想念EF5的哪些方面?
以下是我的触发器代码:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[SetColumn3]
ON [dbo].[Table]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
UPDATE Table
SET Column3 = RTRIM(inserted.Column3) + CAST(inserted.Id + 100 AS nvarchar(10))
FROM inserted
WHERE Table.Id = inserted.Id;
END
答案 0 :(得分:1)
Column3
定义 DatabaseGeneratedOption.Identity
属性。此声明告诉EF在插入期间在数据库中创建了值,并且它必须查询该值。