NickStrupat / EntityFramework.Triggers

Adds events for entity inserting, inserted, updating, updated, deleting, and deleted
MIT License
373 stars 46 forks source link

Query database during trigger on same DbContext? #17

Closed MikeJansen closed 7 years ago

MikeJansen commented 7 years ago

Question:

We have a BinaryObject entity that just contains the ID and data (byte[]) and a BinaryObjectHeader that contains details. The BinaryObject is created first and the data is streamed. The header is created next. I recently added a Size property to the header and would like to automatically set it on Insert trigger to the length of the data.

Can I use the DbContext from the trigger to executable DbContext.Database.SqlQuery<>() during the trigger? The SQL does not affect the data in the context ("SELECT LEN(Data) FROM BinaryObjects WHERE BinaryObjectId = @p0")

NickStrupat commented 7 years ago

Hi @MikeJansen,

Yes, you can do DbContext work inside the trigger. That's actually the main reason I included the DbContext in the trigger delegate :)

Things can get weird if you start putting inserts and updates inside your triggers without being careful, for the somewhat obvious reasons of potentially creating a trigger loop or a chain of trigger logic that is hard to follow.

Anyway, quick SELECT queries like you are suggesting will be fine.