Get all rows using entity framework dbset

c# dbset entity-framework

Question

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.

1
28
6/18/2019 5:20:09 PM

Accepted Answer

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>()

41
12/1/2012 11:17:39 AM

Popular Answer

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)



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow