Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger does not fire after insert using Entity Framework with MVC4 SQL Server

I have following problems.

I use a trigger to do Statistic for my website.

In my Controller I use this code:

 db.MyModel.Add(model);
 db.SaveChanges();

My trigger work well when I insert records in SQL Server Management Studio. But when I insert records from website, my trigger do not fire.

I have similar trigger on other table and all of them work well. I don't know why only this table cause the problem. I also tried to delete edmx file and create it again but still no luck. Is there something that I need to do to make it works?

I'm using Entity Framework 5, MVC4, Visual Studio 2012, MSSQL Server 2008 R2.

Thank you.

UPDATE #1: When insert records from website, new records are saved to database but trigger do not occurs. Program do not generate any errors.

like image 485
Bluer Avatar asked Mar 27 '26 13:03

Bluer


1 Answers

I had the same problem using Entity Framework with SQL Server Database.

For the trigger to be fired on the database you need to send the 'commit' using 'TransactionScope' after 'db.SaveChanges();' command.

I am using the Entity Framework Core library. Here is an example:


using (var ts = new TransactionScope())
{
    using (var db = new DbContext()) // Modify to you Context Class
    {
        // Your logic code
            
        db.MyModel.Add(model);
        db.SaveChanges();
        
        // commit
        ts.Complete();
    }
}
like image 192
RodrigoPatto Avatar answered Mar 30 '26 03:03

RodrigoPatto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!