我有一个sql server数据库,我使用EF 6.0在我的应用程序中访问它。
我有以下SQL查询,我需要将dbcontext linq转换为实体查询,并且很难解决。
这是查询:
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查询
答案 0 :(得分: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();