I created a CLR after trigger like this:
[Microsoft.SqlServer.Server.SqlTrigger(Name = "MyTrigger", Target = "[dbo].[MyTable]", Event = "AFTER INSERT, UPDATE")]
public static void TriggerName()
{
SqlCommand command;
SqlTriggerContext triggContext = SqlContext.TriggerContext;
SqlPipe pipe = SqlContext.Pipe;
SqlDataReader reader;
using (SqlConnection connection
= new SqlConnection(@"context connection=true"))
{
connection.Open();
command = new SqlCommand(@"SELECT * FROM INSERTED;",
connection);
reader = command.ExecuteReader();
while (reader.Read())
{
PopulateDataFromOneRow();
}
reader.Close();
ProcessInsertedData();
}
}
The trigger is supposed to process multiple row inserts. And it works for SQL querys such as
INSERT INTO MyTable SELECT * FROM AnotherTableWithSameSchema;
But when I tried to insert MyTable in Entity Framework using
for(i = 1; i < 30; i++)
{
MyTable myTable = new MyTable();
DoSomeThing();
MyDbContext.MyTables.Add(myTable);
}
MyDbContext.SaveChanges();
The CRL trigger triggers once, but the inserted table only has the last row. I also tried
MyDbContext.MyTables.AddRange(aListOfMyTables);
It has the same problem.
And tried
MyDbContext.Database.ExecuteSqlCommand("INSERT INTO MyTable(...)
VALUES (ROW1), (ROW2)... (ROW30);");
It doesn't seem to work.
How can I insert multiple rows at once in Entity Framework and let the trigger see all rows in the inserted table?
Thanks.