Huma Ali
Huma Ali

Reputation: 1809

Map SQL query results into C# Object

I am looking for any resource that can help me in mapping the query results into my c# objects using WCF. Previously, I was working in LINQ but I need to do it without LINQ. So I was wondering if someone can explain with an example as to how I can achieve the same without LINQ. I googled but couldn't find a nice example for beginners. Any help would be really appreciated.

I have a Product class

public class Product
{
    public int ProductId { get; private set; }
    public string Code { get; private set; }
    public string ProductName { get; private set; }

}

And I want to call a stored procedure usp_Get_Products via WCF service call and ADO.NET

With LINQ I would do it like this in the Service.svn.cs file

public List<Product> GetProducts(string productName,string productCode)
{
  TrsProductDataClassDataContext  db = new TrsProductDataClassDataContext();
  var products = db.usp_Get_Products(productName, productCode);
  return products.ToList();
}

Upvotes: 0

Views: 1543

Answers (1)

Pedro G. Dias
Pedro G. Dias

Reputation: 3222

If you mark your class with the [Serializable] attribute, then WCF will do the translation for you. You can specify in configuration how you'd like to serialize. XML is the default, but to add support for JSON, all you need to do is to add that to your configuration

Important bit in code (I always forget if it's Serializable or DataContract, so I end up using both):

[Serializable, DataContract]
public class Product
{
    public int ProductId { get; private set; }
    public string Code { get; private set; }
    public string ProductName { get; private set; }
}

Important bit in WCF configuration, is to give a default behavior of JSON to the WCF endpoint (if you need it):

  <behaviors>
    <endpointBehaviors>
      <behavior name="setJsonDefault" >
        <webHttp defaultOutgoingResponseFormat="Json" />
      </behavior>
    </endpointBehaviors>
  </behaviors>

And then you simply apply that behaviour to your endpoint (not service). You can now just apply that as a client configuration to your stored proc, and it should work. Just create a client, and you're go.

Upvotes: 1

Related Questions