I have designed an API to get data from different tables using GET
method requests. How to design Get method to get data from different tables?
Here is my controller:
namespace WebAPIDemo.Controllers
{
public class ValuesController : ApiController
{
static public IEnumerable<Product> GetProducts()
{
IList<Product> product = new List<Product>();
SqlConnection conn = new SqlConnection();
Product productInfo = new Product();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
string sqlText = "select * from Products";
SqlCommand sqlCmd = new SqlCommand(sqlText, conn);
conn.Open();
SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read())
{
productInfo.productName = reader[0].ToString();
productInfo.brandName = reader[1].ToString();
productInfo.manufacturingYear= reader[2].ToString();
product.Add(productInfo);
}
conn.Close();
return product;
}
static public IEnumerable<Customer> GetCustomer()
{
IList<Customer> customer = new List<Customer>();
SqlConnection conn = new SqlConnection();
Customer customerProfile = new Customer();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
string sqlText = "select * from customerProfile";
SqlCommand sqlCmd = new SqlCommand(sqlText, conn);
conn.Open();
SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read())
{
customerProfile.customerFirstName = reader[0].ToString();
customerProfile.customerLastName = reader[1].ToString();
customer.Add(customerProfile);
}
conn.Close();
return customer;
}
public IEnumerable<Product> GetAllProducts()
{
return GetProducts();
}
public Product GetProduct(int id)
{
return GetProducts().ElementAt(id);
}
public Customer GetCustomer(int id)
{
return GetCustomer().ElementAt(id);
}
}
}
The GetAllProducts method gives me the following output:
<ArrayOfProduct>
<Product>
<brandName>ParleG</brandName>
<manufacturingYear>2018</manufacturingYear>
<productName>Biscuits</productName>
</Product>
<Product>
<brandName>BMW</brandName>
<manufacturingYear>2018</manufacturingYear>
<productName>Cars</productName>
</Product>
</ArrayOfProduct>
the GetProduct method gives me the following output:
<Product>
<brandName>BMW</brandName>
<manufacturingYear>2018</manufacturingYear>
<productName>Cars</productName>
</Product>
After that I designed GetCustomer method for customer table
public Customer GetCustomer(int id)
{
return GetCustomer().ElementAt(id);
}
it gives me the following error:
Multiple actions were found that match the request: Get on type WebAPIDemo.Controllers.ValuesController GetCustomer on type WebAPIDemo.Controllers.ValuesController.
What changes do I need to make to resolve this error and so that I get values from different tables through API.