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?

1
  • Show how you're calling the method and trying to access the properties. As a side note - here's a question on the pros/cons of returning different collection/query types from repository methods. Commented Jul 27, 2015 at 14:27

1 Answer 1

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.