- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
介绍
我将 EF Core 与 .NET 5.0 和 SQL Server Express 一起使用。基本上我想知道它是否生成了有问题的 SQL 查询,或者我的代码是否有问题(可能是:D)。我在问题的底部提供了一个 mre,但希望问题从我收集的数据中变得明显(我已经问过类似的问题,但觉得它需要彻底改革)
设置
我有一个记录和一个 DbContext
像下面这样。它被剥离到重要的属性 Moment
, 其中 必须类型为 DateTimeOffset
(公司指南)。
private class Foo
{
public int ID { get; set; }
public DateTimeOffset Moment { get; set; }
}
private class Context : DbContext
{
public Context(DbContextOptions<Context> options) : base(options) {}
public DbSet<Foo> Foos { get; set; }
}
生成的数据库中相应列的数据类型为
datetimeoffset(7)
,好像没问题。
context.Foos.Add(new Foo() { Moment = DateTimeOffset.Parse("2021-04-21 00:00 +02:00"), });
context.Foos.Add(new Foo() { Moment = DateTimeOffset.Parse("2021-04-22 00:00 +02:00"), });
context.Foos.Add(new Foo() { Moment = DateTimeOffset.Parse("2021-04-23 00:00 +02:00"), });
context.Foos.Add(new Foo() { Moment = DateTimeOffset.Parse("2021-04-24 00:00 +02:00"), });
context.Foos.Add(new Foo() { Moment = DateTimeOffset.Parse("2021-04-25 00:00 +02:00"), });
现在我想查询所有记录
Moment >= start && Moment <= end
而忽略这些参数的时间:
var start = DateTimeOffset.Parse("2021-04-22 00:00 +02:00");
var end = DateTimeOffset.Parse("2021-04-24 00:00 +02:00");
我希望得到 3 条记录并提出 3 个对我来说似乎相同的查询,但是,第二个产生了不同的结果:
private static async Task Query1(Context context, DateTimeOffset start, DateTimeOffset end)
{
var records = await context.Foos
.Where(foo => foo.Moment.Date >= start.Date && foo.Moment.Date <= end.Date)
//... Finds 3 records, expected
}
private static async Task Query2(Context context, DateTimeOffset start, DateTimeOffset end)
{
start = start.Date; // .Date yields DateTime -> implicit conversion to DateTimeOffset?
end = end.Date;
var records = await context.Foos
.Where(foo => foo.Moment.Date >= start && foo.Moment.Date <= end)
// ... Finds only 2 records, unexpected
}
private static async Task Query3(Context context, DateTimeOffset start, DateTimeOffset end)
{
var start2 = start.Date; // start2 and end2 are of type DateTime now
var end2 = end.Date;
var records = await context.Foos
.Where(foo => foo.Moment.Date >= start2 && foo.Moment.Date <= end2)
// ... Finds 3 records, expected
}
结果
List<Foo>
查询数据。 :
private static void Query1(List<Foo> foos, DateTimeOffset start, DateTimeOffset end)
{
var records = foos
.Where(foo => foo.Moment.Date >= start.Date && foo.Moment.Date <= end.Date)
//...
}
DateTime
与
DateTime
而第二个比较
DateTime
与
DateTimeOffset
.因此,我想知道为什么 LINQ 版本的行为不同。
-- From Query1()
exec sp_executesql N'SELECT [f].[ID]
FROM [Foos] AS [f]
WHERE (CONVERT(date, [f].[Moment]) >= @__start_Date_0) AND (CONVERT(date, [f].[Moment]) <= @__end_Date_1)',N'@__start_Date_0 datetime2(7),@__end_Date_1 datetime2(7)',@__start_Date_0='2021-04-22 00:00:00',@__end_Date_1='2021-04-24 00:00:00'
-- From Query2()
exec sp_executesql N'SELECT [f].[ID]
FROM [Foos] AS [f]
WHERE (CAST(CONVERT(date, [f].[Moment]) AS datetimeoffset) >= @__start_0) AND (CAST(CONVERT(date, [f].[Moment]) AS datetimeoffset) <= @__end_1)',N'@__start_0 datetimeoffset(7),@__end_1 datetimeoffset(7)',@__start_0='2021-04-22 00:00:00 +02:00',@__end_1='2021-04-24 00:00:00 +02:00'
-- From Query3()
exec sp_executesql N'SELECT [f].[ID]
FROM [Foos] AS [f]
WHERE (CONVERT(date, [f].[Moment]) >= @__start2_0) AND (CONVERT(date, [f].[Moment]) <= @__end2_1)',N'@__start2_0 datetime2(7),@__end2_1 datetime2(7)',@__start2_0='2021-04-22 00:00:00',@__end2_1='2021-04-24 00:00:00'
地雷
Microsoft.EntityFrameworkCore
测试和
Microsoft.EntityFrameworkCore.SqlServer
版本
5.0.6
.
namespace Playground
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
public static class Program
{
private class Foo
{
public int ID { get; set; }
public DateTimeOffset Moment { get; set; }
}
private static Context CreateContext()
{
var connectionString = $"Data Source=.\\SQLEXPRESS;Initial Catalog=FOO_DB;Integrated Security=SSPI";
var optionsBuilder = new DbContextOptionsBuilder<Context>();
optionsBuilder.UseSqlServer(connectionString).EnableSensitiveDataLogging();
var context = new Context(optionsBuilder.Options);
context.Database.EnsureCreated();
return context;
}
private class Context : DbContext
{
public Context(DbContextOptions<Context> options) : base(options) { }
public DbSet<Foo> Foos { get; set; }
}
private static async Task Query1(Context context, DateTimeOffset start, DateTimeOffset end)
{
var records = await context.Foos
.Where(foo => foo.Moment.Date >= start.Date && foo.Moment.Date <= end.Date)
.Select(foo => foo.ID)
.ToListAsync();
Console.WriteLine($"Query1 in DB found {records.Count} records");
}
private static async Task Query2(Context context, DateTimeOffset start, DateTimeOffset end)
{
start = start.Date;
end = end.Date;
var records = await context.Foos
.Where(foo => foo.Moment.Date >= start && foo.Moment.Date <= end)
.Select(foo => foo.ID)
.ToListAsync();
Console.WriteLine($"Query2 in DB found {records.Count} records");
}
private static async Task Query3(Context context, DateTimeOffset start, DateTimeOffset end)
{
var start2 = start.Date;
var end2 = end.Date;
var records = await context.Foos
.Where(foo => foo.Moment.Date >= start2 && foo.Moment.Date <= end2)
.Select(foo => foo.ID)
.ToListAsync();
Console.WriteLine($"Query3 in DB found {records.Count} records");
}
public async static Task Main()
{
var context = CreateContext();
var foos = new List<Foo>() {
new Foo() { Moment = DateTimeOffset.Parse("2021-04-21 00:00 +02:00"), },
new Foo() { Moment = DateTimeOffset.Parse("2021-04-22 00:00 +02:00"), },
new Foo() { Moment = DateTimeOffset.Parse("2021-04-23 00:00 +02:00"), },
new Foo() { Moment = DateTimeOffset.Parse("2021-04-24 00:00 +02:00"), },
new Foo() { Moment = DateTimeOffset.Parse("2021-04-25 00:00 +02:00"), },
};
if (!context.Foos.Any())
{
await context.AddRangeAsync(foos);
}
await context.SaveChangesAsync();
var start = DateTimeOffset.Parse("2021-04-22 00:00 +02:00");
var end = DateTimeOffset.Parse("2021-04-24 00:00 +02:00");
await Query1(context, start, end);
await Query2(context, start, end);
await Query3(context, start, end);
context.Dispose();
}
}
}
最佳答案
第二个和其他两个 LINQ 查询之间的区别(因此不同的翻译 - CAST ... as datetimeoffset
)是其他人使用 DateTime
比较,而这使用 DateTimeOffset
比较。因为当start
类型是 DateTimeOffset
, 表达方式
foo.Moment.Date >= start
通过 CLR 类型系统规则(适用于 C# 生成的表达式树)实际上是
((DateTimeOffset)foo.Moment.Date) >= start
与
foo.Moment.Date <= end
相同.
DateTime
的区别至
DateTimeOffset
两个执行上下文之间的转换 - 客户端(CLR)和服务器(在本例中为 SqlServer):
This method is equivalent to the
DateTimeOffse
t constructor. The offset of the resultingDateTimeOffset
object depends on the value of theDateTime.Kind
property of thedateTime
parameter:
If the value of the
DateTime.Kind
property isDateTimeKind.Utc
, the date and time of theDateTimeOffset
object is set equal todateTime
, and its Offset property is set equal to 0.If the value of the
DateTime.Kind
property isDateTimeKind.Local
orDateTimeKind.Unspecified
, the date and time of theDateTimeOffset
object is set equal todateTime
, and itsOffset
property is set equal to the offset of the local system's current time zone.
For conversion to
datetimeoffset(n)
, date is copied, and the time is set to 00:00.0000000 +00:00
Date
属性返回
DateTime
与
Inspecified
kind,然后转换回
DateTimeOffset
使用您本地系统的当前时区偏移量 - 根据您初始化变量的方式,很可能是 +2。而在 SQL 查询中,列值转换为 0 偏移量。从
DateTimeOffset
比较使用所有成员(包括偏移量),对于某些数据值,您可以获得不同的结果。
关于c# - 这个请求是由 EF Core buggy 生成的还是我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67800947/
EF POCO 和 EF Code First 有什么区别? 如果我一开始只使用 POCO,我可以将 EF 与它们一起使用吗? 最佳答案 如果您首先使用 EF 代码,您将拥有 POCO 对象,并且数据
EF POCO 和 EF Code First 有什么区别? 如果我一开始只使用 POCO,我可以将 EF 与它们一起使用吗? 最佳答案 如果您首先使用 EF 代码,您将拥有 POCO 对象,并且数据
我有一个基于 .NET 4.8 和 EF 6.4.4 的项目。我们正在逐步迁移到 .Net Core,但在此过程中我可以创建一个 .NET Core 数据上下文类 EF Core 并将两者指向相同的实
我有以下 Entity Framework 5 代码第一类 public class Airplane { public int Id { get; set; } public int
我正在尝试使用 Entity Framework Core 对现有数据库进行逆向工程.我试着按照指示from Microsoft但我遇到了错误: Unable to find provider ass
当数据库不是由 EF 代码首先创建时,有没有办法检查 DbContext 是否与数据库匹配? 我正在寻找与 Database.CompatibleWithModel 类似的功能但没有元数据。 最佳答案
目前,我正在重构我的上下文方法的测试,以不再需要真正的数据库。我使用 Ef Core。 所以我通读了 Microsoft 文档如何测试上下文方法。我首先找到了 EF6 测试的文档,然后阅读了 EfCo
我正在使用 EF 6 Database.SqlQuery 语句来执行存储过程,并实现错误和事务处理,打开和关闭事务(处理多个记录,如果一个记录有错误,仅回滚此,并提交其他任何内容无错误完成)。 Lis
我首先使用 EF 数据库,因为我喜欢在 SQL Management Studio 中设计我的数据库,坦率地说,让 Visual Studio 直接从数据库创建所有实体非常容易,而无需执行任何代码。
我的项目中有几个迁移文件,由于我对上次迁移进行了手动修改,所以我不想使用“程序包管理器控制台”重新生成它。我只需要添加 1 列。所以在之前的迁移中手动添加了这个(我可以这样做,因为还没有人升级过)。
原文:https://bit.ly/2umidlb 作者:jon p smith 翻译:王亮 声明:我翻译技术文章不是逐句翻译的,而是根据我自己的理解来表述的。其中可能会去除一些本人实在不知道如何组
我们想开始一个新项目,我们决定从一开始就在一些表中使用 Columnstore 索引和聚簇索引,我们如何使用 Code First EF Core 3.1 做到这一点? 最佳答案 您应该将主键更改为非
我在 Entity Framework 6.0 上。这是一个开发问题,而不是生产问题。 我想我有一个相互矛盾的策略。 目前,我设置了 DropCreateDatabaseIfModelChanges
我在 VS 2012 RTM 上,使用 EF 5。我在做代码优先,但由于我只是在开发中,所以试图忽略代码迁移。为了避免它们,我有这一套 Database.SetInitializer(new Drop
我有复杂的审计字段类型 我的复杂类型: [ComplexType] public class AuditData { [Column("CreatorUserId")] public
我已经阅读了很多关于如何在关系中指定外键名称的帖子,没有遇到任何问题。不过,我想知道的是,有没有办法更改主键和关系的命名方式? 例如,您有一个以 UserId 作为主键的 User 表。 EF 代码第
我刚刚安装了新的Entity Framework 4.1 NuGet包,因此根据NuGet指令和this article of Scott Hanselman替换了EFCodeFirst包。 现在,想
我的应用程序基于 .NET 4.0 和 EF 4。我现在正在考虑升级到最新版本。 是否有任何可能对我的申请产生不利影响的重大变化或行为差异? 升级路径有多简单?升级到 EF 5 是否需要任何代码更改或
假设您必须使用 EF Code First 和 POCO 类开发支持多种语言的网站,您将如何对 POCO 类进行建模以支持这种情况? 通过多语言支持,我的意思不仅是拥有例如在一些资源文件中为您的 UI
我首先使用 EF 4.1 代码。鉴于以下类片段: public class Doctor { public virtual ICollection Hospitals { get; set;
我是一名优秀的程序员,十分优秀!