我需要按一年中的周数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/