如何将 SQL 翻译成 C#
How to translate SQL to C#
我有一个 SQL 查询,如下所示:
SELECT
a.Date,
CASE
WHEN a.Type = 'String 1' OR a.Type = 'String 2'
THEN 'foo'
ELSE 'bar'
END AS VisitType,
DATEDIFF (d, (SELECT TOP 1 Date FROM dim.Date WHERE DateKey = a.StartDate),
(SELECT TOP 1 Date FROM dim.Date WHERE DateKey = a.EndDate)) AS Duration
我正在尝试将它转换为 C# 表达式,到目前为止我有这样的东西:
var allowedTypes = new[]{"String 1","String 2", "String 3", "String 4"}
var Data = from a in dbContext.Claim
where a.MemberId = memberId
&& a.StartDate > startDate
&& a.EndDate <= endDate
&& a.Type.Where(???t => allowedTypes.Contains(allowedTypes)) // This line I have issues with
select new
{
Date = a.EndDate,
VisitType = ???,
VisitDuration = ???
}
我在使用 DateDiff 概念和使用字符串数组执行类似 Contains 的方法时遇到困难。
我还意识到日期的类型包含在可为空的 int 中。
感谢您到目前为止的所有建议~!
尝试将条件移动到结果中:
select new
{
Date = a.EndDate,
VisitType = allowedTypes.Contains(a.Type) ? "foo" : "bar",
VisitDuration = ???
}
var result = dbContext.Claims
.Where (claim => claim.MemberId = memberId
&& claim.StartDate > startDate
&& claim.EndDate <= endDate
.Select(claim => new
{
Date = claim.EndDate,
VisitType = allowedTypes.Contains(claim.Type) ? "foo" : "bar",
VisitDuration = claim.EndDate - claim.StartDate,
});
换句话说:给定值 memberId
、startDate
、endDate
。从 Claims 的 table 中,仅保留那些 属性 MemberId 的值等于 memberId,属性 startDate 的值高于 startDate,endDate 的值等于小于结束日期。
从剩余声明序列中的每个声明中,创建一个具有三个属性的新对象。
- 日期是声明的结束日期,
- 持续时间是索赔的结束日期 - 开始日期
- 如果声明的 VisityType 在 allowedTypes 中,则 属性 VisitType 的值为“foo”,否则 VisitType 的值为“bar”
我有一个 SQL 查询,如下所示:
SELECT
a.Date,
CASE
WHEN a.Type = 'String 1' OR a.Type = 'String 2'
THEN 'foo'
ELSE 'bar'
END AS VisitType,
DATEDIFF (d, (SELECT TOP 1 Date FROM dim.Date WHERE DateKey = a.StartDate),
(SELECT TOP 1 Date FROM dim.Date WHERE DateKey = a.EndDate)) AS Duration
我正在尝试将它转换为 C# 表达式,到目前为止我有这样的东西:
var allowedTypes = new[]{"String 1","String 2", "String 3", "String 4"}
var Data = from a in dbContext.Claim
where a.MemberId = memberId
&& a.StartDate > startDate
&& a.EndDate <= endDate
&& a.Type.Where(???t => allowedTypes.Contains(allowedTypes)) // This line I have issues with
select new
{
Date = a.EndDate,
VisitType = ???,
VisitDuration = ???
}
我在使用 DateDiff 概念和使用字符串数组执行类似 Contains 的方法时遇到困难。 我还意识到日期的类型包含在可为空的 int 中。
感谢您到目前为止的所有建议~!
尝试将条件移动到结果中:
select new
{
Date = a.EndDate,
VisitType = allowedTypes.Contains(a.Type) ? "foo" : "bar",
VisitDuration = ???
}
var result = dbContext.Claims
.Where (claim => claim.MemberId = memberId
&& claim.StartDate > startDate
&& claim.EndDate <= endDate
.Select(claim => new
{
Date = claim.EndDate,
VisitType = allowedTypes.Contains(claim.Type) ? "foo" : "bar",
VisitDuration = claim.EndDate - claim.StartDate,
});
换句话说:给定值 memberId
、startDate
、endDate
。从 Claims 的 table 中,仅保留那些 属性 MemberId 的值等于 memberId,属性 startDate 的值高于 startDate,endDate 的值等于小于结束日期。
从剩余声明序列中的每个声明中,创建一个具有三个属性的新对象。
- 日期是声明的结束日期,
- 持续时间是索赔的结束日期 - 开始日期
- 如果声明的 VisityType 在 allowedTypes 中,则 属性 VisitType 的值为“foo”,否则 VisitType 的值为“bar”