将值从CLR触发器传递到WCF

本文关键字:WCF 触发器 CLR | 更新日期: 2023-09-27 18:20:55

不知怎么的,当插入新记录时,我找不到如何正确传递数据,正在将第一列值发送回WCF。一切正常,但我无法传递数据。我错过了什么?

调用WCF:的CLR触发器

public partial class Triggers
{
    public static EndpointAddress endpoint =  new EndpointAddress(new Uri("http://localhost:8000/services/myservice"));
    public static WSHttpBinding httpBinding = new WSHttpBinding();
    public static ServiceClient.ServiceReference1.ServiceContractClient myclient = new ServiceClient.ServiceReference1.ServiceContractClient(httpBinding, endpoint);
    public delegate void MyDelagate(String crudType);
    [SqlProcedure()]
    public static void SendData(String crudType)
    {
        myclient.UpdateOccured();//i was trying to pass the crudType value here 
    }
    [Microsoft.SqlServer.Server.SqlTrigger(Name = "WCFTrigger", Target = "tbCR", Event = "FOR INSERT")]
    public static void Trigger1()
    {
        SqlCommand cmd;
        SqlTriggerContext myContext = SqlContext.TriggerContext;
        SqlPipe pipe = SqlContext.Pipe;
        SqlDataReader reader;
        if(myContext.TriggerAction== TriggerAction.Insert)
        {
            using (SqlConnection conn = new SqlConnection(@"context connection=true"))
            {
                conn.Open();
                cmd = new SqlCommand(@"SELECT * FROM tbCR", conn);
                reader = cmd.ExecuteReader();
                reader.Read();
                //get the insert value's here
                string Name;
                Name = (string)reader[1];
                reader.Dispose();

                switch (myContext.TriggerAction)
                {
                    case TriggerAction.Update:
                         SendData(Name);
                        break;
                    case TriggerAction.Insert:
                        SendData(Name);
                    break;
                }
            }
        }
    }
}

我的服务合同:

namespace SampleService
{
    class MyService : IServiceContract
    {
        public void UpdateOccured()
        {
            Console.WriteLine("Update Occured");
        }
        public void InsertOccured(string Name)
        {
            Console.WriteLine("Insert Occured",Name);
        }
    }
}

接口:

namespace SampleService
{
    [ServiceContract]
    interface IServiceContract
    {
        [OperationContract]
        void UpdateOccured();
        [OperationContract]
        void InsertOccured(string Name);
    }
}

将值从CLR触发器传递到WCF

您应该从实际表的INSERTED插入头中进行选择,即

cmd = new SqlCommand(@"SELECT * FROM INSERTED", conn);

此外,您应该显式地命名所需的列,而不是使用*。

INSERTED和DELETED以及SQL Server创建的内存驻留表。

更多详细信息

删除的表存储DELETE和期间受影响行的副本UPDATE语句。执行DELETE或UPDATE期间语句,行将从触发器表中删除并传输到删除的表。通常删除的表和触发表没有共同的行。

插入的表在INSERT期间存储受影响行的副本和UPDATE语句。在插入或更新事务期间,新建行被添加到插入的表和触发器表中。这个插入表中的行是触发器中新行的副本桌子

更新事务类似于删除操作,后面跟着插入操作;首先将旧的行复制到已删除的表中,然后将新行复制到触发器表和插入的表。