Return only one field from a list in WCF

7

The method is like this:

public List<CivarTransporteService.Model.Cliente> getClientes()
{
   using (CivarTransporteService.Model.CivarTransporteModelContainer context = 
               new Model.CivarTransporteModelContainer())
   {
            return context.Cliente.ToList();                
   }
}

the cs like this:

public interface ICatalogsService
{
    [OperationContract]
    List<CivarTransporteService.Model.Cliente> getClientes();
}

obviously it returns all the data in the table, but I just need the name field, how can I do it?

    
asked by jm167 21.01.2016 в 03:56
source

2 answers

4

I offer you 2 variants:

1- For the name of a single client:

(eye! you need a client ID)

Using Linq, filter the client by its identifier and return the name, then make the operation return a string: (this method returns null if the client does not exist)

public String getNombreCliente(int idCliente) {
    using (CivarTransporteService.Model.CivarTransporteModelContainer context = 
           new Model.CivarTransporteModelContainer())
    {
        return (from c in context.Cliente
                where c.id == idCliente 
                select c.nombre).FirstOrDefault();
    }
}

2- For the list of names:

public List<String> getNombreClientes(int idCliente) {
    using (CivarTransporteService.Model.CivarTransporteModelContainer context = 
           new Model.CivarTransporteModelContainer())
    {        
        return (from c in context.Cliente
                select c.nombre).ToList();
    }
} 

Explanation:

Notice that in both cases the trick is in select , asking for c.nombre (which I assume is a String ) causes the Linq command to return a IEnumerable<String> instead of IEnumerable<CivarTransporteService.Model.Cliente>

Then with ToList() we convert it into a list type List<String> just what we want to return.

By the way, in the first example using FirstOrDefault I indicate the IEnumerable<String> that returns the first record or null if there are no results.

The operations of the WCF service must return the same type as the query functions.

public interface ICatalogsService
{
    [OperationContract]
    String getNombreCliente(int idCliente);

    [OperationContract]
    List<String> getNombreClientes();
}

Here is a link with more information about linq: link

    
answered by 21.01.2016 / 04:10
source
2

I add a variant to the response of @mmeverdies but with lambda expression :

public String getNombreCliente(int idCliente) {
    using (CivarTransporteService.Model.CivarTransporteModelContainer context = 
           new Model.CivarTransporteModelContainer())
    {
        return context.Cliente.Where(c => c.id == idCliente)
                      .Select(c => c.nombre)
                      .FirstOrDefault();

    }
}

Examples linq (in English):

101 LINQ Samples

Linq Lambda expression samples

    
answered by 21.01.2016 в 13:38