c# - 如何在 Entity Framework Core 中按周数排序?

标签 c# .net entity-framework-core

我需要按一年中的周数OrderBy DbSet。就像 T-SQL 中的 iso_week datepart ( https://learn.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql?redirectedfrom=MSDN&view=sql-server-ver16#iso_week-datepart )。

可以在 Entity Framework 6 中使用 SqlFunctions.DatePart(),但是,在 EF Core 中没有这样的方法。

那么如何在 EF 核心中使用 LINQ 的 OrderBy 和 WeekOfYear?

最佳答案

默认情况下,它并未内置到 EF Core 中,但您可以创建自己的函数映射。假设这是在 .NET 6 中,您可以执行如下操作:

public class MyDbContext : DbContext
{
    //snip other stuff

    // Add a stub method we can use later...
    public int? DatePart(string datepart, DateTime? date) => throw new NotImplementedException();

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        // Get a reference to the stub method
        var methodInfo = typeof(MyDbContext)
            .GetRuntimeMethod(nameof(DatePart), new[] { typeof(string), typeof(DateTime?) });

        // Now tell the context how to map the stub method to the actual SQL
        builder
            .HasDbFunction(methodInfo)
            .HasTranslation(args =>
            {
                var datepartFragment = new SqlFragmentExpression(((SqlConstantExpression)args[0]).Value.ToString());
                var datePropertyFragment = new SqlFragmentExpression(((ColumnExpression)args[1]).Name);

                return new SqlFunctionExpression(
                    nameof(DatePart),
                    new SqlExpression[] { datepartFragment, datePropertyFragment },
                    true,
                    new[] { true, true },
                    typeof(int?),
                    RelationalTypeMapping.NullMapping
                );
            });
    }

}

现在您可以像这样在 Linq 查询中调用此方法:

var products = _context.Products
    .Select(p => new 
    {
        Name = p.Name,
        IsoWeekCreated = _context.DatePart("iso_week", p.DateCreated) // <--- The clever bit here
    })
    .ToList();

关于c# - 如何在 Entity Framework Core 中按周数排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74095772/

相关文章:

c# - 我应该为创建和更新使用不同的DTO吗? (CRUD)

.net - 在 .NET 中创建具有动态属性数量的数据模型的最佳方法

entity-framework - 在 Entity Framework 核心中选择不加载导航属性后包含

c# - 将 XmlRoot 或 XmlType 与 RestSharp 结合使用

c# - RabbitMQ - QueueDeclare 永远挂起

c# - 在两台计算机之间进行 .NET 远程处理时出现套接字错误

c# - "Using"语句如何从 C# 转换为 VB?

entity-framework - 如何处置 Entity Framework Core 内存数据库

.net-core - 使用 ModelBuilder 在 EFCore5 中播种多对多数据库?

c# - 在 C# 中轻松绘制空心 donut 形状的任何方法