1

I'm trying to query a db set, but I can't seem to access the data when I get the results. Here is the code I've tried.

Query #1:

public List<CustomerMain> testing()
{
        var context = new CustomerEntities();

        var query = context.CustomerMains
            .Where(p=> p.FirstName == "Thor")
            .Select(p => new CustomerMain {FirstName=p.FirstName,LastName =p.LastName}).ToList();

        return query;
}

Query #2:

public IQueryable<CustomerMain> testing()
{
        var context = new CustomerEntities();

        var query = context.CustomerMains
            .Where(p=> p.FirstName == "Thor")
            .Select(p => new CustomerMain {FirstName=p.FirstName,LastName =p.LastName});

        return query;
}

CustomerMain is my DbSet, If I run either of those and assign the method to a var variable, it gives me no options to grab the FirstName or LastName from the variable. I found I can do it if I convert it to a CustomerMain, but shouldn't the return query be in a CustomerMain type already?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dylan
  • 1,068
  • 12
  • 25
  • Show how you're calling the method and trying to access the properties. As a side note - [here's a question](http://stackoverflow.com/questions/11307171/ef-icollection-vs-list-vs-ienumerable-vs-iqueryable) on the pros/cons of returning different collection/query types from repository methods. – D Stanley Jul 27 '15 at 14:27

1 Answers1

5

it gives me no options to grab the FirstName or LastName from the variable

Because the method returns a collection or queryable, not a single entity. You need to iterate or select records:

var customers = testing();
foreach (CustomerMain customer in customers)
{
    // access customer.FirstName
}

Or:

var customers = testing();
var oneCustomer = customers.FirstOrDefault(c => c.FirstName == "Thor");
// access oneCustomer.FirstName

Or, if you want the method to return one record (or null if none found):

public CustomerMain FindOne(string firstName)
{
    using (var context = new CustomerEntities())
    {    
        var query = context.CustomerMains.Where(p => p.FirstName == firstName);

        return query.FirstOrDefault();
    }
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272