我希望我解决了触发器的问题。根据所有文档,如果我在 C# 中进行插入或升级(通过模式 Reposity),触发器必须返回一个值。这适用于简单的触发器。
如果我使用更复杂的触发器,则返回值会出错。
a) 如果从触发器SELECT @@identity 返回;
System.Int32 类型的成员,这是一种不允许空值的值类型。您不能将值分配给 Null。
b) 如果从触发器返回:select * from dbo.Table where IDColumn = scope_identity();
Operation failed AutoSync member. In order to perform after insertion members operation
AutoSynced must have a type either automatically generated identity, or a key that does
not change the database after the insertion.
使用:C#、.NET FW4.5、Linq to SQL、MSSQL Express 2012(兼容性 2008)
我会很高兴以及有关触发器和链接到 SQL 的问题的指示。
更复杂的触发器(清理并减少到最低限度):
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[bitrgTable]
ON [dbo].[Table]
INSTEAD OF INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT OFF;
-- Declare variables
DECLARE @new...
-- Get inserted values
SELECT @new... FROM INSERTED
-- do update all unique values
UPDATE [dbo].[Table] SET
...
WHERE
...;
-- if the last result is null
IF @@ROWCOUNT = 0
BEGIN
-- Do insert new values
INSERT INTO [dbo].[Table]
(...)
SELECT
...
FROM INSERTED
END
-- somehow return the result
-- ----------------------------------------------------------------
-- select * from dbo.table where TableID = scope_identity();
-- SELECT @@identity;
SELECT ??????
END
最好的问候,彼得
基于 Ismet Alkan 补充问题的答案。
// Reposity class
public class Reposity
{
private DataContext myDataContext = new DataContext();
public void Save()
{
myDataContext.SubmitChanges();
}
}
// Where working with reposity (class in console app)
public class ConsoleShell
{
// declare variable
Reposity myReposity = new Reposity();
// Many methods, working with treads etc,
// here I worked with Save()
private void ExecuteThread(....)
{
...
// go thŕow all found results
foreach (KeyValuePair<Oid, AsnType> kvpDot1dTpFdbAddress in dictDot1dTpFdbAddress)
{
// create new object instance
CustomObjectFromLinq objCustomObjectFromLinq = new CustomObjectFromLinq();
// append values for objCustomObjectFromLinq
if(CONDITION == TRUE)
{
// save item
myReposity.Add(objCustomObjectFromLinq);
myReposity.Save();
}
else
{
// if want ignore result, do nothing, prevent object null
objCustomObjectFromLinq = null;
}
.. next codes
} -- end foreach
} -- end method
} -- end class