1
var model = from m in db.Customers
            orderby m.a descending
            select new Get_Complaint_Form_Sub
            {
                CustomerFullName = m.a,
                Email = m.Email_Address,
                PhoneNumber = m.Telephone_No
            };

I am using this LINQ query to retrieve selected columns in db. It fetches the last record in the table in descending order

DavidG
  • 113,891
  • 12
  • 217
  • 223
Dexter
  • 69
  • 1
  • 10

2 Answers2

0

It sounds like the problem here is downstream, i.e. something that is consuming model. In particular, it sounds like it is expecting one N, not a query of them. So... you might want to add .SingleOrDefault(), .FirstOrDefault(), .Single() or .First() to your query (depending on what you intended). For example:

var query = from m in db.Customers
        orderby m.a descending
        select new Get_Complaint_Form_Sub
        {
            CustomerFullName = m.a,
            Email = m.Email_Address,
            PhoneNumber = m.Telephone_No
        };
var model = query.FirstOrDefault();

As a more general note: an IQueryable<T> is usually a pending query - it hasn't been executed yet. Most times that you are talking about a model, you'd want to be talking about rigid data; so if you were trying to represent some number of N, you should probably use .ToList() or .ToArray() to evaluate the query and populate a list/array.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

As suggested by Marc, the problem is not with your Linq query, but rather it is in your MVC view. The error message you posted is telling you that your view (i.e. your .cshtml file) is expecting one type but you are passing into it another. It looks like you have made the common mistake of passing in an enumeration of values instead of a single value. Your solution is either:

  • Pass in a single value to your view by using Single(), `First() etc.
  • Fix your view so it takes IEnumerable<T> instead of just T, and update the code within to deal with that accordingly.
Community
  • 1
  • 1
DavidG
  • 113,891
  • 12
  • 217
  • 223