【问题标题】:How to translate SQL to C#如何将 SQL 转换为 C#
【发布时间】:2023-03-06 01:35:01
【问题描述】:

我有一个如下所示的 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 中。

感谢您迄今为止的所有建议~!

【问题讨论】:

  • .First() 或 .FirstOrDefault() 是替换 SELECT TOP 1 的好考虑
  • 可空整数中的日期?您的数据库服务器可能会尝试这样做,但实体框架肯定不会。不要将日期存储为 int,这只是糟糕的设计。
  • 我认为Claim.StartDate.EndDate 是日期表的外键???为什么不直接将日期值放在表格中?
  • @JeremyLakeman 那完全是另外一罐蠕虫。哈哈

标签: c# entity-framework linq


【解决方案1】:
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。

从剩余声明序列中的每个声明中,创建一个具有三个属性的新对象。

  • 日期是索赔的结束日期,
  • Duration 是声明的 EndDate - StartDate
  • 如果 Claim 的 VisityType 在 allowedTypes 中,则属性 VisitType 的值为“foo”,否则 VisitType 的值为“bar”

【讨论】:

    【解决方案2】:

    尝试将条件移动到结果中:

    select new
    {
       Date = a.EndDate,
       VisitType = allowedTypes.Contains(a.Type) ? "foo" : "bar",
       VisitDuration = ???
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 2017-09-19
      相关资源
      最近更新 更多