简体   繁体   English

dbcontext 上的实体框架选择子句

[英]Entity framework select clause on a dbcontext

Is it possible to have a select clause on a dbcontext.set.是否可以在 dbcontext.set 上使用 select 子句。 I have the following code that returns all coinsurance of People in a db table and selects all columns.我有以下代码返回数据库表中 People 的所有共同保险并选择所有列。

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

I only want to select username and email我只想选择用户名和电子邮件

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

In both your example, and Jason's example, you should be aware of the fact that you are passing the context-aware object.在您的示例和 Jason 的示例中,您应该意识到您正在传递上下文感知对象这一事实。 Further manipulations of data may cause unexpected hits against the database.对数据的进一步操作可能会导致对数据库的意外命中。 Also when you are doing a function like DbContext.Set() you are doing the slowest form of database call in EF.此外,当您执行像 DbContext.Set() 这样的函数时,您正在执行 EF 中最慢的数据库调用形式。 For the fastest and most effecient database call you would do as follows:要获得最快和最有效的数据库调用,您可以执行以下操作:

 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 is the fastest form of EF use.原始 SQL 是 EF 使用最快的形式。 Almost as fast as raw ADO.NET.几乎和原始 ADO.NET 一样快。

Here:这里:

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

and you want to filter resaults, add some overloads for example:如果您想过滤结果,请添加一些重载,例如:

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

If you want to retrieve the object person :如果要检索对象 person :

Add a constructor in the "Person" class在“Person”类中添加构造函数

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

And modify this method并修改此方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM