【问题标题】:SQL Virtual Column in LinqLinq 中的 SQL 虚拟列
【发布时间】:2018-04-02 23:21:06
【问题描述】:

有没有办法在 C# dotnetcore MVC 页面中使用 Razor 页面和实体框架在 linq 查询中创建等效的 SQL 虚拟/计算列...

SELECT 0 as 'sortField'
FROM
    database
WHERE
    foo = bar

...但是使用方法语法,形成这样的形式?:

Foo = await
(
    _context.Foo
        .Where(r => !StatusExceptionList.Contains(r.Status))
        .Where(r => (Convert.ToDateTime(r.Statusdate) - today).TotalDays < 31)
        .Where(r => r.DSRPID == PID)
        .OrderBy(r => r.Submitteddate)
        .ThenBy(r => r.Statusdate)
        .ThenBy(r => r.recordnum)
)
.Union
(
_context.Foo
    .Where(r => !DraftStatusExceptionList.Contains(r.Status))
    .Where(r => r.DSRPID == PID)
    .Where(r => r.csstatus != "not needed" || !String.IsNullOrEmpty(r.csstatus))
    .Where(r => !_context.Foo
                .Where(rr => rr.DSRPID == PID)
                .Select(rr => rr.Fooid)
                .Contains(r.Fooid)
          )
     .OrderBy(r => r.Submitteddate)
     .ThenBy(r => r.Statusdate)
     .ThenBy(r => r.recordnum)
)
.ToListAsync();

【问题讨论】:

    标签: c# sql entity-framework linq


    【解决方案1】:

    我相信你可以这样做:

    class TableResults
    {
      public int sortField
    }
    
    from t in context.Table select new TableResults { sortField = 0 }
    

    因此,您必须有一个具有名为 sortField 的属性的类。

    【讨论】:

    • 你也可以使用匿名对象:from d in database where foo == bar select new { sortField = 0 }
    • 是的。根据您想对对象执行的操作,它可能会有些混乱,因此我通常会创建类。
    • 感谢您的回复,我试图让它工作,但我的查询使用的是方法语法,而且我对 C# 有点陌生,所以我不是超级流利并解决语法问题我试图用你的帖子弄清楚。如果有人有任何进一步的想法,我更新了主帖子以显示我现在正在使用的代码!
    • 如果没有更多关于数据库结构的上下文,很难给出更好的答案。此外,您可能还有其他一些问题。如果您要进行联合,则需要在两个查询中选择相同的列,或者至少在每个点中选择相同类型的值。
    【解决方案2】:

    您可以在 linq 中使用如下匿名类型

    from result in database
    where foo = bar
    select new { sortField=0 }
    

    【讨论】:

    • 感谢您的回复,我试图让它工作,但我的查询使用方法语法,我对 C# 有点陌生,所以我不是超级流利并解决语法问题我试图用你的帖子弄清楚。如果您有任何进一步的想法,我更新了主要帖子以显示我现在正在使用的代码!再次感谢您。
    【解决方案3】:

    相当于 SQL 虚拟/计算列将是只读属性。

    如果实例包含计算其值所需的所有值,您可以在实体类中执行此操作

    public class Foo
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int SortValue => Id == 42 ? 0 : Id;
    }
    
    _context.Foo.Where(f => somecondition)
                .OrderBy(f => f.SortValue)
                .ToList();
    

    如果实例没有计算所需的所有值,您可以使用匿名类型

    _context.Foo.Where(f => somecondition)
                .Select(f => new
                {
                    Id = f.Id,
                    Name = f.Name,
                    SortValue = f.Name == "External name" ? 0 : 1
                })
                .OrderBy(f => f.SortValue)
                .ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 2013-02-19
      相关资源
      最近更新 更多