c# - 在存在触发器的情况下从 linq 到 sql 向 sql server 插入行时出错

标签 c# sql-server linq-to-sql triggers insert

我在sql server中为下表创建了一个触发器,

Buildings: ID decimal(24, 0) PK, Name varchar(255)

触发器是

CREATE TRIGGER [dbo].[TRG_BLD]
   ON  [dbo].[Building] 
   INSTEAD OF INSERT
AS 
BEGIN
    INSERT INTO Building (Name)
    SELECT Name
    FROM inserted
END

它所做的一切,只是将行插入表中(它做的更多,但我正在努力简化我的案例)。

当我从 sql server 插入一行时,一切正常, 但是当我通过 LinqToSql 插入时,

Building b = new Building();
b.Name = "building A";
DC.Buildings.InsertOnSubmit(b);
DC.SubmitChanges();

“SubmitChanges”发生异常说:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.Linq.dll

Additional information: The null value cannot be assigned to a member with type System.Decimal which is a non-nullable value type.

最佳答案

IF OBJECT_ID('dbo.Building', 'U') IS NOT NULL
    DROP TABLE dbo.Building
GO
CREATE TABLE dbo.Building
(
    ID INT IDENTITY(1,1) PRIMARY KEY,
    Name VARCHAR(255)
)
GO
CREATE UNIQUE NONCLUSTERED INDEX ix ON dbo.Building (Name) WITH(IGNORE_DUP_KEY=ON)
GO

CREATE TRIGGER dbo.TRG_BLD
   ON  dbo.Building
   INSTEAD OF INSERT
AS 
BEGIN

    SET NOCOUNT ON;

    INSERT INTO dbo.Building (Name)
    SELECT Name
    FROM INSERTED

END
GO

INSERT INTO dbo.Building (Name)
VALUES ('a'), ('a'), ('b'), ('c'), (NULL), (NULL)
GO

SELECT *
FROM dbo.Building

输出-

ID          Name
----------- ------------
1           a
3           b
4           c
5           NULL

关于c# - 在存在触发器的情况下从 linq 到 sql 向 sql server 插入行时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34417003/

相关文章:

c# - Net Core : Difference between . Startup.Cs 中的 SetBasePath 和 .UseContentRoot

sql - 游标和存储过程优化

c# - T-SQL 到 LINQ 的转换

c# - ASP.NET HttpContext 项目在服务器上消失

c# - 如何获取字符串的一部分

c# - 从 C# 发送邮件时使用 To 或 CC - 在性能方面哪个更好?

sql-server - 使用强类型数据集重试 SQL Azure 请求

sql-server - 使用 SQL Server/SSIS 数据导入向导导入 Varbinary(max) 数据?

c# - Linq to sql Repository pattern , 一些问题

linq-to-sql - 确认 LINQ to SQL 更新成功