C#将sql查询转换为EF dbcontext linq到实体查询

问题描述 投票:0回答:1

我有一个SQL Server数据库,我使用EF 6.0在我的应用程序中访问它。

我有以下SQL查询,我需要转换为dbcontext linq到实体查询,并有一些该死的困难时间弄明白。

enter image description here

这是查询:

select 
PA.Number, 
PA.Name,  
PR.* 
from MYDBNAME.dbo.Product PR 
join MYDBNAME.dbo.Order OD on PR.Id = OD.Id 
join MYDBNAME.dbo.Payment PA on OD.Id = PA.Id 
where PR.Year = 2017
and PR.StatusId = (select CD.Id from Code CD where CodeId = (select ST.Id 
from Status ST where ST.Value = 'Done')
and CD.State = 'Completed') 
and PA.Created = '2018-12-10' 
and PR.Amount <= 500


class Product
{
public string Id { get; set; }
public string Name { get; set; }
public decimal Amount { get; set; }
public string StatusId { get; set; }
public int Year {get; set;}
} 


class Order
{
public string Id { get; set; }

} 

class Payment
{
public string Id { get; set; }
public DateTime Created { get; set; }
public decimal Amount { get; set; }
public string Number { get; set; }
public string Name { get; set; }
} 

class Status
{
  public string Id { get; set; }
public string Value { get; set; }
} 

class Code
{
public string Id { get; set; }
public string CodeId { get; set; }
public string State { get; set; }
} 

由于State和Code类与其余类无关,我想应该单独运行子查询,然后为主查询发出另一个dbcontext查询

c# sql linq entity-framework-6 linq-to-entities
1个回答
0
投票

您的SQL等效LINQ查询是,

string statusValue = "Done";
string codeState = "Completed";
DateTime paDate = DateTime.ParseExact("2018-12-10", "yyyy-MM-dd", new CultureInfo("en-US", true));
int year = 2017;
decimal amount = 500;

var result = (from PR in context.Products
              join OD in context.Orders on PR.Id equals OD.Id
              join PA in context.Payments on OD.Id equals PA.Id

              let codeId = (from ST in context.Status where ST.Value == statusValue select ST.Id).FirstOrDefault()
              let statusId = (from CD in context.Codes where CD.Id == codeId && CD.State == codeState select CD.Id).FirstOrDefault()

              where PR.Year == year
              && PR.StatusId == statusId
              && PA.Created == paDate
              && PR.Amount <= amount
              select new
              {
                  Number = PA.Number,
                  Name = PA.Name,
                  PR = PR
              }).GroupBy(x => x.Number).Select(x => x.First()).ToList();
© www.soinside.com 2019 - 2024. All rights reserved.