EF6 -> 等效于 EF Core ExecuteSqlCommand

EF6 -> EFCore ExecuteSqlCommand equivelant

我正在努力将我们的模型移至 EF Core,但我无法找到调用以下代码的方法:

InitializeTime = context.ExecuteSqlCommand<DateTime>("SELECT CURRENT_TIMESTAMP FROM DUAL").FirstOrDefault();

我们使用数据库时间来同步所有内容,但据我所知,在 DbSet 之外调用原始 sql 不可用,并且 return 类型仅限于 DbSet类型参数。

我环顾四周,发现有 DbQuery 个对象 (Article),但这似乎只是为了获取当前系统日期时间而进行的繁重工作。

有没有其他人遇到过这个问题并找到了更简单的解决方案?

注意:这是一个桌面应用程序,因此代码将是 运行 客户端,系统日期时间不可靠。

与 EFCore 同名的 context.Database.ExecuteSqlRaw(sql)/context.Database.ExecuteSqlRInterpolated(sql)(或 context.Database.ExecuteSqlCommand(sql) 在 EFCore 3 之前,您尚未指定您正在使用的版本)只能 return 一个 int,执行 sql 语句影响的行数。

context.Query<TQuery>()(直到 EFCore 3,从 EFCore 3 开始弃用)或由普通 POCO 支持的无密钥实体(EFCore 3 开始)是据我所知,如果您想使用EFCore 执行查询。

Keyless Entity Types 多科:

Usage scenarios

Some of the main usage scenarios for keyless entity types are:

Serving as the return type for raw SQL queries.

就开销而言,当您考虑 EFCore 实现的 work/repository 模式的单位时,它并不是真正的;它实质上会迫使您实施一个存储库,而不是在这个地方进行临时查询。

以防有人遇到同样的问题。我最终得到以下结果:

创建一个包含 DateTime 属性

的新 class
public class SystemDateTime
{
    /// <summary>
    /// System datetime from the server.
    /// </summary>
    public DateTime DateTime { get; set; }
}

SystemDateTime 类型的 DbSet 添加到模型中

    /// <summary>
    /// Set for getting the current date time from the database.
    /// </summary>
    public DbSet<SystemDateTime> SystemDateTimes { get; set; }

注意:在 EFCore 3.1 中,它需要是 DbSet 类型,但在 EFCore 2 中。?有一种专门用于这种集合的不同类型称为 DbQuery。见文章 Here.

将映射添加到模型构建器

modelBuilder.Entity<SystemDateTime>().HasNoKey();
modelBuilder.Entity<SystemDateTime>().Property<DateTime>(x => x.DateTime).HasColumnName(@"DateTime").HasColumnType(@"TIMESTAMP").IsRequired().ValueGeneratedNever();

使用DbSetFromSqlRaw查询数据库

List<SystemDateTime> systemDateTime = context.SystemDateTimes.FromSqlRaw("SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') \"DateTime\" FROM DUAL").ToList();

这将 return 一个元素的列表,因此使用 First()Single 来获取所需的值。