Instead of triggers in MS SQL and Entity Framework problem

I don’t like the model of instead of and after triggers in MS SQL. The before and after ones are, in my opinion, better. Anyway I needed to do some complex tests, not possible with check constraints, before inserting. Hence I jumped into instead of trigger. No problem in a view. Or not?

The Entity Framework is smart enough to get all server generated columns back when inserting (or updating) – see StoreGeneratedPattern. But the problem is how the identity column, often used for primary keys, is retrieved. The command issued after insert looks like (particular shape depends on other store generated columns and concurrency checks): select <PK column> from <some table> where @@ROWCOUNT > 0 and <PK column> = scope_identity().The problem is, that if you generate new PK value in trigger, it is different scope. Thus this command returns zero rows and EF will throw exception.

Hmm, this isn’t the way. :( So one of the solutions is move away from instead of triggers and use stored procedures (remember that you need all three) and result binding (you might be forced to create SPs (of fake ones in SSDL) for some related objects too). It’s not easiest solution, but works nice and you don’t have to introduce hacks etc.

  • Twitter
  • Facebook
  • Share/Bookmark
This entry was posted in .* and tagged , . Bookmark the permalink.

2 Responses to Instead of triggers in MS SQL and Entity Framework problem

  1. Vašek Nauš says:

    Zdravim,

    narazil jsem na stejný problém a bohužel přendání do procedur není možné. Chtěl jsem se zeptat, jestli náhodou tento problém neřeší EF 4…

    Děkuji, Vašek

    PS: snad nevadí, že píšu CZ pod EN článek, když píšu člověku, co vládne češtinou :-)

  2. cincura.net says:

    Upravy v EF4 jsou, ale pouze pro datove typy krome int, u nehoz bylo chovani zachovano pro zpetnou kompatibilitu.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>