Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework, view and instead of insert trigger. Can't insert a row into the view

I can't insert an entity into the mapped view. The error I get is:

Store, insert or delete statement affected an unexpected number of rows (0)

I know how to use stored procedures, but it is more interesting for me to try a solution with an instead of trigger on insert row view event. I don't get any error when I delete, update or insert in t-sql code, but I can't INSERT a row using EF. Update and delete work in EF, but INSERT doesn't.

Code:

create view TestInsert
as
    select a.table_id, a.name
    from TableA as a

create trigger tr_works_via_tsql_but_not_ef_for_some_reason
on TestInsert
instead of isert
begin
   insert into TableA (table_id, name)
   select table_id, name from inserted;
end
[Table(TestInsert)]
public class TestInsert
{
   [Key]
   public int table_id { get; set; }
   public string name { get; set; }
}

Can anyone help me?

like image 526
user1572418 Avatar asked Dec 06 '22 23:12

user1572418


1 Answers

Hooray, I have found the solution! The body of instead of trigger must return an id for the table.

create trigger tr_works_via_tsql_but_not_ef_for_some_reason
on TestInsert
instead of isert
begin
   insert into TableA (table_id, name)
   select table_id, name from inserted;

   **select id from TableA where @@ROWCOUNT > 0 and id = scope_identity()**
end

I use direct mapping and there is no edmx file in my project. This is the source of the answer: Entity Framework with Instead Of triggers

like image 54
user1572418 Avatar answered May 18 '23 13:05

user1572418