WCF, MySQL and Transaction

2019-09-22 08:38发布

问题:

I am having a problem in MySql.Data.MySqlClient.MySqlTransaction in a Windows Communication Foundation Server Application.

I am using the MySqlTransaction inside the method of the class that implements the ServiceContract Interface and it throws this error when I try to run the service:

System.Runtime.Serialization.InvalidDataContractException: Type 'MySql.Data.MySqlClient.MySqlTransaction' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute.

My code in WCF service was simmilar to this:

[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();
    }
}

The error occur just by typing the http://localhost:1257/DALService.svc in my web browser.

I am using Framework 4, code in C#, in Microsoft Visual Studio 2010 Pro.

Please help. Thanks in advance.

回答1:

This can't be the code that's causing an issue. The error you are getting is coming from an attempt to return or pass in a MySqlTransaction to/from the service. That's just simply not going to work.

Also, why on earth are you exposing a Command object to the outside world via a public property? Furthermore, it doesn't even appear that you use it... Delete that property and keep your command scoped to the method that uses it. If you don't and you run this service as a singleton, you'll get lots of crazy bugs.

Even furthermore... This is an extremely dangerous service to expose. If you were to have someone use it other than yourself, it provides zero encapsulation. Heck, you might as well just open up a port directly to the SQL Server, as dumb as that sounds.