Reputation: 4883
I'm new to c#, so hopefully I can give you enough information here.
I am trying to return a list of products, where the product status column has a value of 1.
But, I keep hitting a my catch, and returning null.
I would like to create a list for each product, but I have not even got that far yet, currently just dumping the results into a viewdata.
The exception I am getting on the catach is: Invalid operation...:Cannot order by type 'Davey.Models.GetAllProducts'.
Here is my code:
My Model: (Product Model)
namespace Davey.Models
{
[DataContract]
public class GetAllProducts
{
[DataMember]
public string ID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Desc { get; set; }
[DataMember]
public string Price { get; set; }
[DataMember]
public string Points { get; set; }
[DataMember]
public string Cat { get; set; }
[DataMember]
public string SizeS { get; set; }
[DataMember]
public string SizeM { get; set; }
[DataMember]
public string SizeL { get; set; }
[DataMember]
public string SizeXL { get; set; }
[DataMember]
public int Status { get; set; }
}
}
My Service (DaveyService.scs): // This is where I keep hitting the catch block
public GetAllProducts[] AllProducts(int status)
{
try
{
using (UserDataDataContext db = new UserDataDataContext())
{
return db.mrobProducts.Where(x => x.Status == status).Select(x => new GetAllProducts { Name = x.Name, Desc = x.Description, Price = x.Price }).OrderBy(x => x).ToArray();
}
}
catch
{
return null;
}
}
And my controller, which has been cut down to the relevant part:
[HttpPost]
[AllowAnonymous]
public ActionResult UserLogin(LoginModel model, UserName usernameModel, GetAllProducts allProductsModel)
{
if (userExists)
{
var webService3 = new DaveyServiceClient();
allProductsModel.Status = 1;
ViewData["products"] = webService.AllProducts(allProductsModel.Status);
return View("../Private/Index");
}
return View("Index");
}
Upvotes: 1
Views: 210
Reputation: 149598
The problem is that your OrderBy
method doesn't know how to sort by GetAllProducers
.
You have two choices:
IComparable<GetAllProducts>
in GetAllProducts
Sort by something OrderBy
will know how to sort by, like a string
or an int
, for example:
using (UserDataDataContext db = new UserDataDataContext())
{
return db.mrobProducts.Where(x => x.Status == status).Select(x => new GetAllProducts
{
Name = x.Name,
Desc = x.Description,
Price = x.Price
}).OrderBy(x => x.Price).ToArray();
}
As a side note, i usually like to specify what im catching in my catch
clause, as you should always do something with the exception you catch, even if its just logging. I suggest you use a specific type like catch (InvalidOperationException e)
or if you really need a general catch then catch (Exception e)
Upvotes: 1
Reputation: 39023
You're getting the exception because you're ordering by a complex type. Do ...OrderBy(x=>x.Name)
, or by any other field you want to sort by.
Upvotes: 1