WCF服务返回一个不可序列化的对象

时间:2015-09-29 14:01:56

标签: c# wcf serialization

我设置了这样的WCF服务:

IService1.cs

namespace AzureWebServiceTest
{    
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        void createCloudAccount(string accountName);

        [OperationContract]
        SqlConnection useDb();
    }
}

Service1.cs

namespace AzureWebServiceTest
{
public class Service1 : IService1
{
    public void createCloudAccount(string accountName)
    {
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1");
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference(accountName);
        container.CreateIfNotExists();
    }

    public SqlConnection useDb()
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = "Server=localhost;Database=StilistaLibrary;Trusted_Connection=true";
        return conn;
    }
}
}

但是我对useDB()的返回类型有问题,我认为因为SqlConnection是一个不可序列化的对象,我该如何才能正确设置这个服务呢?

1 个答案:

答案 0 :(得分:2)

您似乎误解了要为其引入网络服务的内容。

您当然将数据库连接对象从服务返回到客户端。您可以使用服务从客户端封装和抽象数据库。

您可以向服务添加GetRecordsForCustomer(int customerID)等方法,然后让客户端调用它。您不返回数据库对象,而是从服务中收集数据。

这样您不仅可以更改基础数据存储(即交换数据库,或更常见,更改您的数据模型而不会影响您的客户端),但您还可以添加其他行为,而无需拥有程序触发器和数据库上的程序。

如果您希望您的客户直接访问数据库,则您无需使用Web服务。