C# 如何使用实体框架选择单列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9054609/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:44:37  来源:igfitidea点击:

How to select a single column with Entity Framework?

c#entity-framework

提问by SeToY

Is there a way to get the entire contents of a single column using Entity Framework 4? The same like this SQL Query:

有没有办法使用实体框架 4 获取单个列的全部内容?与此 SQL 查询相同:

SELECT Name FROM MyTable WHERE UserId = 1;

采纳答案by Christofer Eliasson

You can use LINQ's .Select()to do that. In your case it would go something like:

您可以使用 LINQ.Select()来做到这一点。在你的情况下,它会是这样的:

string Name = yourDbContext
  .MyTable
  .Where(u => u.UserId == 1)
  .Select(u => u.Name)
  .SingleOrDefault(); // This is what actually executes the request and return a response

If you are expecting more than one entry in response, you can use .ToList()instead, to execute the request. Something like this, to get the Name of everyone with age 30:

如果您期望收到多个条目作为响应,您可以.ToList()改为使用来执行请求。像这样的事情,要得到每个 30 岁的人的名字:

string[] Names = yourDbContext
  .MyTable
  .Where(u => u.Age == 30)
  .Select(u => u.Name)
  .ToList();

回答by M.Babcock

You could use the LINQ selectclause and reference the property that relates to your Name column.

您可以使用 LINQselect子句并引用与您的 Name 列相关的属性。

回答by Clayton

Using LINQ your query should look something like this:

使用 LINQ,您的查询应如下所示:

public User GetUser(int userID){

return
(
 from p in "MyTable" //(Your Entity Model)
 where p.UserID == userID
 select p.Name
).SingleOrDefault();

}

Of course to do this you need to have an ADO.Net Entity Model in your solution.

当然,要做到这一点,您的解决方案中需要有一个 ADO.Net 实体模型。

回答by Jawid Hassim

I'm a complete noob on Entity but this is how I would do it in theory...

我是 Entity 的完全菜鸟,但这就是我理论上的做法......

var name = yourDbContext.MyTable.Find(1).Name;

If It's A Primary Key.

如果是主键。

-- OR --

- 或者 -

var name = yourDbContext.MyTable.SingleOrDefault(mytable => mytable.UserId == 1).Name;

-- OR --

- 或者 -

For whole Column:

对于整个列:

var names = yourDbContext.MyTable
.Where(mytable => mytable.UserId == 1)
.Select(column => column.Name); //You can '.ToList();' this....

But "oh Geez Rick, What do I know..."

但是“哦,Geez Rick,我知道什么......”