dbcontext上的实体框架select子句

时间:2012-12-04 19:19:45

标签: c# entity-framework

是否可以在dbcontext.set上使用select子句。我有以下代码,它返回db表中People的所有共存保险并选择所有列。

public IQueryable<Person> GetPeople()
{
    return DbContext.Set<Person>();                
}

我只想选择用户名和电子邮件

4 个答案:

答案 0 :(得分:8)

var projection = GetPeople().Select(p => new {p.Username, p.Email});

答案 1 :(得分:2)

在您的示例和Jason的示例中,您应该知道您正在传递上下文感知对象。进一步处理数据可能会导致对数据库的意外命中。此外,当您执行像DbContext.Set()这样的函数时,您正在使用EF中最慢的数据库调用形式。对于最快和最有效的数据库调用,您可以执行以下操作:

 public List<GetPersonResult> GetPeople()
 {
       return (from p in dbContext.People
              select new GetPersonResult
              {
                   UserName = p.Username,
                   EmailAddress = p.Email
              }).ToList();
 }

 public class GetPersonResult
 {
       public string UserName{get;set;}
       public string EmailAddress{get;set;}
 }

Raw SQL是EF使用的最快形式。几乎与原始ADO.NET一样快。

答案 2 :(得分:0)

下面:

public IQueryable<Person> GetPeople()
{
    return DbContext.Set<Person>().Select(per => new {per.UserName, per.Email})                
}

并且您希望过滤resaults,添加一些重载,例如:

public IQueryable<Person> GetPeople()
{
    return DbContext.Set<Person>().Select(per => new {per.UserName, per.Email})                
}

public IQueryable<Person> GetPeople(int cityId)
{
    return DbContext.Set<Person>().Where(p => p.CityID == cityId)
               .Select(per => new {per.UserName, per.Email})                
}

答案 3 :(得分:0)

如果要检索对象人员:

在“人”类中添加一个构造函数

    public Person(string UserName, string EmailAddress){
      This.UserName = UserName;
      This.EmailAddress = EmailAddress;}

并修改此方法

public IQueryable<Person> GetPeople()
{
    return DbContext.Set<Person>()
                    .Select(per => new Person(per.UserName, per.Email));                 
}