如何为以下SQL Server查询编写实体框架

时间:2018-04-17 11:57:18

标签: c# sql-server entity-framework

我需要在Entity Framework中编写以下SQL Server查询,但到目前为止还没有成功。有人可以帮助转换为Entity Framework语法吗?

SQL表

username, date,      value
--------------------------
brad,     1/2/2010,  1.1
fred,     1/3/2010,  1.0
bob,      8/4/2009,  1.5
brad,     2/2/2010,  1.2
fred,     12/2/2009, 1.3

SQL Server查询

select t.username, t.date, t.value
from MyTable t
inner join (
    select username, max(date) as MaxDate
    from MyTable
    group by username
) tm on t.username = tm.username and t.date = tm.MaxDate

原始问题在这里:https://stackoverflow.com/a/2411703/1355975

2 个答案:

答案 0 :(得分:1)

假设您的数据库基类是DatabaseContext并且您有一个名为MyTable的表,您可以通过以下方式从中选择记录:

using (var context = new DatabaseContext()) 
{ 
    var myTableRecords = context.MyTable.SqlQuery("your query goes in here").ToList(); 
}

您可以这种方式运行任何RAW SQL。

答案 1 :(得分:1)

我认为这就是我正在寻找的 - 我需要稍微量身定做,但应该为我提供我需要的东西:

<div class="col-6">
                    <div class="form-group">

                        <mat-form-field floatLabel="never">
                          <mat-placeholder class="placeholder">Organisation</mat-placeholder>
                          <input type="text" matInput formControlName="filterOrganisation" [matAutocomplete]="auto" value="">
                        </mat-form-field>

                        <mat-autocomplete #auto="matAutocomplete" (optionSelected)="onSelect()">
                          <mat-option *ngFor="let organisation of filteredOrganisations | async" [value]="organisation.Name">
                            {{ organisation.Name }}
                          </mat-option>
                        </mat-autocomplete>


                    </div>
                  </div>
                  <div class="col-6">
                    <div class="form-group">

                        <mat-form-field floatLabel="never">
                          <mat-placeholder class="placeholder">Countires</mat-placeholder>
                          <input type="text" matInput formControlName="filterCountries" [matAutocomplete]="auto2" value="">
                        </mat-form-field>

                        <mat-autocomplete #auto2="matAutocomplete" (optionSelected)="onSelect()">
                          <mat-option *ngFor="let country of filteredCountries | async" [value]="country.Name">
                            {{ country.Name }}
                          </mat-option>
                        </mat-autocomplete>


                    </div>
                  </div>

https://stackoverflow.com/a/37757982/1355975