WCF,MySQL和Transaction

时间:2012-01-24 04:24:12

标签: c# mysql wcf .net-4.0

我在Windows Communication Foundation Server应用程序中的MySql.Data.MySqlClient.MySqlTransaction中遇到问题。

我在实现ServiceContract接口的类的方法中使用MySqlTransaction,当我尝试运行服务时它会抛出此错误:

  

System.Runtime.Serialization.InvalidDataContractException :无法序列化类型“MySql.Data.MySqlClient.MySqlTransaction”。请考虑使用DataContractAttribute属性对其进行标记,并使用DataMemberAttribute属性标记要序列化的所有成员。如果类型是集合,请考虑使用CollectionDataContractAttribute标记它。

我在WCF服务中的代码与此类似:

[ServiceContract]
public interface IDALService
{
    MySqlCommand Command { [OperationContract] get; [OperationContract] set; }

    [OperationContract]
    void Execute(string cmdText);
}

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class DALService : IDALService
{
    public MySqlCommand Command { get; set; }

    public DALService()
    {
        Command = null;
    }

    public void Execute(string cmdText)
    {
        MySqlCommand SQLCom = this.Command??new MySqlCommand();
        SQLCom.CommandText = cmdText;

        if (this.Command == null)
        {
            SQLCom.CommandType = CommandType.Text;
            SQLCom.Connection = new MySqlConnection(/* ... */);
            SQLCom.Connection.Open();
            SQLCom.Transaction = SQLCom.Connection.BeginTransaction();
        }

        if (this.Command == null)
        {
            try
            {
                SQLCom.ExecuteScalar();
                SQLCom.Transaction.Commit();
            }
            catch { SQLCom.Transaction.Rollback(); throw; }
            finally { SQLCom.Connection.Close(); }
        }
        else SQLCom.ExecuteScalar();
    }
}

只需在我的网络浏览器中输入http://localhost:1257/DALService.svc即可发生错误。

我在Microsoft Visual Studio 2010专业版中使用C#中的Framework 4代码。

请帮忙。 提前谢谢。

1 个答案:

答案 0 :(得分:2)

这不是导致问题的代码。您获得的错误来自于尝试将MySqlTransaction返回或传入服务。那只是根本无法发挥作用。

另外,为什么你要通过公共财产向外界公开一个Command对象呢?此外,它甚至没有出现你使用它...删除该属性并将命令范围限定为使用它的方法。如果你不这样做而且你以单身人士的身份运行这项服务,你将会遇到很多疯狂的错误。

更进一步......这是一项非常危险的服务。如果你有人使用它而不是你自己,它提供零封装。哎呀,你也可以直接打开一个端口到SQL Server,就像听起来一样愚蠢。