I have a CF class:
public class A
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id {get;set;}
[Required]
public string Name {get;set;}
public string LoweredName {get;set;}
[Timestamp]
public byte[] RowVersion {get;set;}
}
In the database i have a trigger:
CREATE TRIGGER IOI_LoweredName
ON Abc
INSTEAD OF INSERT
AS;
BEGIN;
SET NOCOUNT ON;
INSERT INTO Abc(Name, LoweredName) SELECT Name, LOWER(Name) FROM inserted
END;
Now if i try to insert a record:
dc.Names.Add(new A { Name = "Test" });
dc.SaveChanges();
I get the following error:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
Any ideas how to get around this?
All my classes inherit from a base class that has the RowVersion (Timestamp) column. Can’t i use such a simple trigger with EF when using concurrency on a timestamp field ?
Updated
There is a primary key (also added it to the example above).
Update 2
This is from the SQL Profiler:
declare @0 nvarchar(100)
set @0=N'Test'
insert [dbo].[abc]([Name], [LoweredCompanyName]) values (@0, null)
select [Id], [RowVersion] from [dbo].[Abc] where @@ROWCOUNT > 0 and [Id] = scope_identity()
Problem is that the select doesn’t return anything.
That entity doesn’t have primary key. EF will not like it.
To fix the current error try to add this at the end of your trigger:
If you change your code to support auto generated PK, you will use this instead:
I’m not sure if this will actually work with instead of trigger but it was necessary when mapping stored procedures to modification operations in EDMX.
Currently it is possible that this operation will be executed by EF directly but it will not count records created or modified by trigger because trigger executes in different scope – that can be a big problem.