Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework with Instead Of triggers

I am using EF with a SQL Server database. I created a view and an Instead Of Insert trigger for that view which looks like this:

insert into Target (value, someFk) 
select value, 4 from inserted
select id from Target where @@ROWCOUNT > 0 and id = scope_identity() 

I mapped the view into an EF edmx. When I try to add an entity I get the following exception when I call SaveChanges():

Unable to update the EntitySet 'TargetView' because it has a DefiningQuery and no element exists in the element to support the current operation.

The view has an identity column marked in the mapping.

Any suggestions?

like image 489
Jaster Avatar asked Aug 31 '12 14:08

Jaster


People also ask

What is the difference between insert and trigger in Entity Framework?

Instead of trigger is executed instead of Insert operation created by Entity framework. This can be potential problem because once you are using identity column each insert is followed by: select [Id] from [dbo]. [TableXXX] where @@ROWCOUNT > 0 and [Id] = scope_identity ()

What is entityframeworkcore triggered?

EntityFrameworkCore.Triggered is a NuGet package that does just that. The source can be found over on Github . This is part 1 in a series on EntityFrameworkCore.Triggered Having worked on different projects involving Entity Framework, I noticed a pattern where we often want to do ‘something’ in response to an action. Some examples of that are:

What is an INSTEAD OF trigger in SQL?

An INSTEAD OF trigger is a trigger that allows you to skip an INSERT, DELETE, or UPDATE statement to a table or a view and execute other statements defined in the trigger instead. The actual insert, delete, or update operation does not occur at all. In other words, an INSTEAD OF trigger skips a DML statement and execute other statements.

What do we need to enable triggers in EF Core?

Luckily for us, EF Core already provides the necessary infrastructure to embrace triggers. All we need to add is a bit of plumbing. EntityFrameworkCore.Triggered is a NuGet package that does just that. The source can be found over on Github . This is part 1 in a series on EntityFrameworkCore.Triggered


1 Answers

If you open EDMX file with an xml editor, in the section where TargetView is defined you will have some xml similar to the following;

<EntitySet Name=".."  
           EntityType=".." 
           store:Type="Views" 
           store:Schema=".." 
           store:Name="..">
<DefiningQuery>SELECT ....</DefiningQuery>

You need to change this xml section in order to have CRUD operations;

<EntitySet Name=".."  
           EntityType=".."  
           store:Type="Tables" 
           Schema=".." />
like image 199
daryal Avatar answered Sep 27 '22 20:09

daryal