C# 使用实体框架 dbset 获取所有行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13658862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get all rows using entity framework dbset
提问by Wesley Skeen
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.
请原谅我,因为我对 EF 完全陌生。
采纳答案by Sergey Berezovskiy
Set<T>()is already IQueryable<T>and it returns all rows from table
Set<T>()is alreadyIQueryable<T>并且它返回表中的所有行
public IQueryable<Company> GetCompanies()
{
return DbContext.Set<Company>();
}
Also generated DbContextwill have named properties for each table. Look for DbContext.Companies- it's same as DbContext.Set<Company>()
还生成DbContext了每个表的命名属性。寻找DbContext.Companies- 它与DbContext.Set<Company>()相同
回答by Not loved
The normal way to do this is by instantiating your dbContext.
执行此操作的正常方法是实例化您的 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)
有很多关于使用 CodeFirst Entity 框架的很好的教程(如果你有一个 DbContext 并且是新的,我假设你正在使用)
回答by Artekat
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();
}
}

