43

I want to select all rows from a table using the following type of syntax:

public IQueryable<Company> GetCompanies()
{
    return DbContext.Set<Company>()
    .// Select all
}

Forgive me as I am completely new to EF.

3 Answers 3

59

Set<T>() is already IQueryable<T> and it returns all rows from table

public IQueryable<Company> GetCompanies()
{
    return DbContext.Set<Company>();    
}

Also generated DbContext will have named properties for each table. Look for DbContext.Companies - it's same as DbContext.Set<Company>()

Sign up to request clarification or add additional context in comments.

2 Comments

Does this not need async?
It does not need async, but it is compatible with it.
23

The normal way to do this is by instantiating your dbContext.

For example:

public IQueryable<Company> GetCompanies()
{
    using(var context = new MyContext()){ 
        return context.Companies;
    }
}

There are lots of good tutorials on using CodeFirst Entity framework (which i assume you are using if you have a DbContext and are new)

Comments

10

I prefer work on list, also have all relations here

For example:

public List<Company> GetCompanies()
{
    using (var context = new MyContext())
    {
        return context.Companies.ToList();
    }
}

1 Comment

Use .ToListAsync() if you want to do this asynchronously and avoid the blocking call

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.