webworm
webworm

Reputation: 11019

Returning fields from multiple entities from ASP.NET Web API v2

I am building an ASP.NET Web API v2 project where I am using Entity Framework v6 to model the database. So far I have been able to return a collection of objects only when the collection is of one object type. i.e. <Customer> or <Order>.

I would like to return a collection of objects but include a field (or property) from a related entity (an association is present). I think I have the LINQ to Entity query setup properly but I am not sure how to return the resultant anonymous type to the jQuery method that calls the API.

[Route("api/clients/GetAllClientsWithPaymentMethod")]
[HttpGet]
public NOT-SURE-WHAT-RETURN-TYPE-SHOULD-BE GetAllClientsWithPaymentMethod()
{
  using (var context = new MyEntities())
  {
    context.Configuration.ProxyCreationEnabled = false;
    var query = from client in context.Clients
                select new
                {
                  ClientID = client.ID,
                  CompanyName = client.CompanyName,
                  Phone = client.Phone,
                  Email = client.email
                  PaymentMethod = client.payments.PaymentMethod
                };
    return query.ToList();
  }
}

Is an anonymous type the proper way to return this information? If so, what should the return type be? Is there a better way to do this?

Upvotes: 0

Views: 1563

Answers (1)

Trisk
Trisk

Reputation: 593

I would make a class called Client that has all the fields you would like to return.

e.g.

public class Client
{
    private int ID;
    private string companyName;
    private string phoneNumber;
    private string email;
    private string payMethod;


    public Client()
    {
    }

    //...etc

}

In the controller I would create a group of client objects from the results of the database query and then I would just return an IEnumerable of clients e.g.

public IEnumerable<Client> GetAllClientsWithPaymentMethod()

On the client side you can read the content of the message with the serializer that you are using.

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("api/clients/GetAllClientsWithPaymentMethod");

IEnumerable<Client> returnedClients = response.Content.ReadAsAsync<Client>(new[] { JsonFormatter() }).Result;

Upvotes: 1

Related Questions