簡體   English   中英

如何將 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 概念時遇到困難,並且使用字符串數組執行包含類似方法。 我也意識到日期的類型包含在一個可為空的 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,
    });

換句話說:給定memberIdstartDateendDate的值。 從 Claims 表中,僅保留屬性 MemberId 的值等於 memberId、Property startDate 的值高於 startDate 和 endDate 的值小於 endDate 的那些 Claims。

從剩余聲明序列中的每個聲明中,創建一個具有三個屬性的新 object。

  • 日期是索賠的結束日期,
  • Duration 是索賠的 EndDate - StartDate
  • 如果 Claim 的 VisityType 在 allowedTypes 中,則屬性 VisitType 的值為“foo”,否則 VisitType 的值為“bar”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM