EntityFrameworkCore.SqlServer.DateDiff

SQL Server DATEDIFF function support for Entity Framework Core


Keywords
datediff, entityframeworkcore, sqlserver, date, diff, entity, framework, core, entity-framework-core, ef, ef.core, sql, server
License
MIT
Install
Install-Package EntityFrameworkCore.SqlServer.DateDiff -Version 1.0.0

Documentation

EntityFrameworkCore.SqlServer.DateDiff

Entity Framework Core for SQL Server comes without suport for familiar DATEDIFF function. This library tries to fill this gap.

Disclaimer

As far as I know, there is no "official" way to extend EF.Core to use DATEDIFF. The way used here is a pure hack. It may break with the next EF.Core release. Use with caution.

Installation

Install NuGet package using command line:

Install-Package EntityFrameworkCore.SqlServer.DateDiff

Or add manually to the projects.json:

{
    "dependencies": {
        "EntityFrameworkCore.SqlServer.DateDiff": "1.0.0"
    }
}

How to use

  • Register DbContext extension in Startup class:
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyContext>(opt => opt
        .UseSqlServer("<my_connection_string>")
        .UseSqlServerDateDiff());
}
  • Use an appropriate DateDiff function (Year, Month, Minute, Second etc.) within your queries:
public void Foo(MyContext db)
{
    // ...

    db.MyTable
        .Select(row => DateDiff.Second(row.StartDateTime, row.EndDateTime))

    // ...
}

License

Copyright (c) 2016 Dmytro Gokun dmytro.gokun@gmail.com.

This package has MIT license. Refer to the LICENSE for detailed information.