身份'component_type_name'的成员在元数据集合中不存在.\ r \nParameter name:identity

Jon*_*nuz 3 sql-server triggers entity-framework

在数据库中,我有一个名为SERVICE的表.对于这个表,我在INSER/UPDATE/DELETE之后有触发器.当我尝试使用EF将记录插入数据库时​​,我得到错误"元素集合中不存在具有标识的成员'component_type_name'.\ r \nParameter name:identity"."component_type_name"列在SERVICE表中不存在,但在表COMPONENT_TYPES_IN_SERVICE中.这是表SERVICE的插入触发器.当我从表中删除触发器时,插入时没有任何问题.

CREATE TRIGGER [dbo].[UpdateComponentTypesInServiceOnInsert]
   ON [dbo].[SERVICE] 
   AFTER INSERT
AS 
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

DECLARE @componentID int;
SET @componentID = 0;

DECLARE @ComponentTypeID int;
SET @ComponentTypeID = 0;

DECLARE @ComponentTypeName nvarchar(255);
SET @ComponentTypeName = null;

SELECT @componentID = component_id from inserted;

SELECT @ComponentTypeID = c.component_type_id, @ComponentTypeName = ct.description from COMPONENTS c
inner join dbo.COMPONENT_TYPES ct on c.component_type_id = ct.id
WHERE c.id = @componentID; 

Select * from COMPONENT_TYPES_IN_SERVICE cts
where cts.id = @ComponentTypeID;

IF (@@ROWCOUNT > 0)
    BEGIN
        UPDATE COMPONENT_TYPES_IN_SERVICE
        SET number_of_components = number_of_components + 1
        WHERE id = @ComponentTypeID;
    END
ELSE
    BEGIN
        INSERT INTO COMPONENT_TYPES_IN_SERVICE(id, component_type_name, number_of_components)
        VALUES (@ComponentTypeID, @ComponentTypeName, 1); 
    END
END
Run Code Online (Sandbox Code Playgroud)

有谁知道任何解决方案???

Lad*_*nka 5

你不能做这个:

Select * from COMPONENT_TYPES_IN_SERVICE cts
where cts.id = @ComponentTypeID;
Run Code Online (Sandbox Code Playgroud)

它将COMPONENT_TYPES_IN_SERVICE记录返回给您的应用程序,EF尝试将返回的值复制到其中,SERVICE因为它认为您正在传回一些数据库生成的值.