{"id":22065806,"url":"https://github.com/karenpayneoregon/ef-core-5-dates-csharp","last_synced_at":"2026-05-04T23:31:35.705Z","repository":{"id":110840497,"uuid":"408243482","full_name":"karenpayneoregon/ef-core-5-dates-csharp","owner":"karenpayneoregon","description":"Working with dates for Entity Framework Core 5","archived":false,"fork":false,"pushed_at":"2022-02-06T21:47:01.000Z","size":100,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-23T18:17:26.253Z","etag":null,"topics":["csharp","efcore","entity-framework-core","sql-server"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/karenpayneoregon.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-09-19T21:44:18.000Z","updated_at":"2022-02-06T21:45:51.000Z","dependencies_parsed_at":null,"dependency_job_id":"3b4348ec-a203-4b48-bf1f-3ff7ae140123","html_url":"https://github.com/karenpayneoregon/ef-core-5-dates-csharp","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/karenpayneoregon/ef-core-5-dates-csharp","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fef-core-5-dates-csharp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fef-core-5-dates-csharp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fef-core-5-dates-csharp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fef-core-5-dates-csharp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/karenpayneoregon","download_url":"https://codeload.github.com/karenpayneoregon/ef-core-5-dates-csharp/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fef-core-5-dates-csharp/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263841595,"owners_count":23518484,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csharp","efcore","entity-framework-core","sql-server"],"created_at":"2024-11-30T19:22:05.843Z","updated_at":"2026-05-04T23:31:35.657Z","avatar_url":"https://github.com/karenpayneoregon.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Entity Framework Core working with dates\n\nProvides several useful examples for working with `dates` in `Entity Framework Core 5`, `SQL-Server` using `C#` with Windows Forms although the base code presented can be used in other project types.\n\n### More samples will be added over time.\n\n![Screen1](assets/screen1.png)\n\nThis solution provides:\n\n- Code sample to display a DateTimePicker in a DataGridView loaded using Entity Framework Core 5.\n  - From the basic code shown, it's easy to provide add, edit, delete, filtering and searching which are not shown to keep things basic. Several other projects will be added to step through add, edit, delete, filtering and searching building up the initial code sample.\n- Code sample for obtaining data using an extension methof for dates between a specific date. \n\n\n\nThe code sample has been built off the following two repositories.\n\n- [WinForms DataGridView with EF Core 5](https://github.com/karenpayneoregon/efcore-datagridview-ToBindingList)\n  - For an overview see the repositories [readme.md](https://github.com/karenpayneoregon/efcore-datagridview-ToBindingList/blob/master/readme.md)\n- [DataGridView custom columns C#](https://github.com/karenpayneoregon/datagridview-custom-columns)\n- Microsoft TechNet article [Windows forms DataGridView dates and numeric columns](\n \n\n# Requires\n\n- Microsoft Visual Studio 2019 or higher\n- .NET 5 or higher\n- C# 9 or higher\n- Microsoft Entity Framework Core 5.x\n- Microsoft SQL-Server (good to have SQL-Server Management Studio)\n\n### Create/populate database\n\nScript to run is script.sql in the DataScripts folder off the root of the solution. Before running inspect the path the database will be created as different versions of SQL-Server may have a different location.\n\n### Connection to database\n\nBy default when reverse engineering a database via scaffolding the connection string is hard coded in the DbContext, in this code sample the connection string is read from the following json files, appsettings.json.\n\n```json\n{\n  \"database\": {\n    \"DatabaseServer\": \".\\\\SQLEXPRESS\",\n    \"Catalog\": \"DateTimeDatabase\",\n    \"IntegratedSecurity\": \"true\",\n    \"UsingLogging\": \"true\"\n  }\n}\n```\n\n**Code in Context class**\n\n```csharp\nprotected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)\n{\n    if (!optionsBuilder.IsConfigured)\n    {\n        optionsBuilder.UseSqlServer(BuildConnection());\n    }\n}\n\nprivate static string BuildConnection()\n{\n\n    var configuration = new ConfigurationBuilder()\n        .AddJsonFile(\"appsettings.json\", true, true)\n        .Build();\n\n    var sections = configuration.GetSection(\"database\").GetChildren().ToList();\n\n    return\n        $\"Data Source={sections[1].Value};\" +\n        $\"Initial Catalog={sections[0].Value};\" +\n        $\"Integrated Security={sections[2].Value}\";\n\n}\n```\n\n\n### Extension methods for querying dates between\n\nWe must use `IQueryable` for deferred execution (Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required). Or write the, in this case conventional perdicate directly in a [Enumerable.Where Method](https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where?view=net-5.0). To keep business code clean and reusable these extension do the trick.\n\n\n```sharp\n\npublic static class DateExtensionHelpers\n{\n\n    public static IQueryable\u003cEvents\u003e BetweenStartDate(this IQueryable\u003cEvents\u003e events, DateTime startDate, DateTime endDate) \n        =\u003e events.Where(@event \n            =\u003e startDate \u003c= @event.StartDate \u0026\u0026 @event.StartDate \u003c= endDate);\n\n    public static IQueryable\u003cEvents\u003e BetweenEndDate(this IQueryable\u003cEvents\u003e events, DateTime startDate, DateTime endDate)\n        =\u003e events.Where(@event \n            =\u003e startDate \u003c= @event.EndDate \u0026\u0026 @event.EndDate \u003c= endDate);\n\n    public static IQueryable\u003cBirthdays\u003e BirthDatesBetween(this IQueryable\u003cBirthdays\u003e events, DateTime startDate, DateTime endDate)\n        =\u003e events.Where(@event\n            =\u003e startDate \u003c= @event.BirthDate \u0026\u0026 @event.BirthDate \u003c= endDate);\n\n\n}\n```\n\nTo filter a table with birthdays in BirthdayForm `BirthDatesBetween` extension above is used.\n\n```csharp\npublic static Task\u003cList\u003cBirthdays\u003e\u003e GetBirthdaysList(DateTime startDate, DateTime endDate) \n    =\u003e Task.Run(async () \n        =\u003e await Context.Birthdays.BirthDatesBetween(startDate, endDate)\n            .OrderBy(birthday =\u003e birthday.BirthDate).ToListAsync());\n```\n\nIn BirthdayForm Shown event a date range is pre-defined. For a real application the range may be defined with two DateTimePickers or custom date selector.\n\n```csharp\nvar startDate = new DateTime(1953, 1, 2);\nvar endDate = new DateTime(1956, 9, 24);\n\n_birthdaysList = new BindingList\u003cBirthdays\u003e(\n    await DataOperations.GetBirthdaysList(startDate, endDate));\n```\n\n**Comment** If the hard coded dates are changed then validate the results in SSMS.\n\n### DataGridView with calendar column\n\nIn EventsForm, data is loaded into a BindingList, DataGridView columns are predefined in the grid designer. When working with dates in a DataGridView this using a custom column for dates is user friendly, if a time column is needed see the following repository [DataGridView custom columns](https://github.com/karenpayneoregon/datagridview-custom-columns).\n\n- This is a read-only demonstration, see learn how to perform add, edit, delete see the following repository [WinForms DataGridView with EF Core 5](https://github.com/karenpayneoregon/efcore-datagridview-ToBindingList).\n- There is a DateTimePicker data bound to the data which implements INotifyPropertyChanged which when changing a date does not reflect in the DataGridView while changing the date in the DataGridView updates the DateTimePicker which means there is an issue with data binding with a DateTimePicker so to fix this the following code is needed.\n\n```csharp\nprivate void BirthDateDateTimePickerOnValueChanged(object sender, EventArgs e)\n{\n    if (DataIsNotAccessible()) return;\n\n    var current = (Person1)_bindingSource.Current;\n\n    current.BirthDate = BirthDateDateTimePicker.Value;\n\n}\n```\n\n# Calclulating age\n\nA common task is to determine the age of a person See under LanguageExtensions, Helper class which provides this ability to calculate age along with Age class under Classes folder.\n \n\n### Resources\n\n- [Microsoft Entity Framework Core documentation](https://docs.microsoft.com/en-us/ef/)\n- [DbFunctions Class](https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbfunctions?view=efcore-5.0), Provides CLR methods that get translated to database functions when used in LINQ to Entities queries. The methods on this class are accessed via [Functions](https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.ef.functions?view=efcore-5.0#Microsoft_EntityFrameworkCore_EF_Functions).\n- [Function Mappings of the Microsoft SQL Server Provider](https://docs.microsoft.com/en-us/ef/core/providers/sql-server/functions)\n- [Microsoft Entity Framework Core 5 logging](https://github.com/karenpayneoregon/ef-core5-logging)\n- [EF Core Power Tools](https://marketplace.visualstudio.com/items?itemName=ErikEJ.EFCorePowerTools): EF Core Power Tools is a Visual Studio extension that exposes various EF Core design-time tasks in a simple user interface. It includes reverse engineering of DbContext and entity classes from existing databases and SQL Server DACPACs, management of database migrations, and model visualizations. For EF Core: 3, 5, 6.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkarenpayneoregon%2Fef-core-5-dates-csharp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkarenpayneoregon%2Fef-core-5-dates-csharp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkarenpayneoregon%2Fef-core-5-dates-csharp/lists"}