{"id":22065572,"url":"https://github.com/karenpayneoregon/sql-server-computed-columns","last_synced_at":"2026-03-07T08:33:12.400Z","repository":{"id":110840650,"uuid":"579789697","full_name":"karenpayneoregon/sql-server-computed-columns","owner":"karenpayneoregon","description":"Using SQL-Server computed columns with EF Core","archived":false,"fork":false,"pushed_at":"2024-05-18T11:40:14.000Z","size":638,"stargazers_count":13,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-06-01T15:02:57.393Z","etag":null,"topics":["computed-columns","csharp","csharp-core","efcore7"],"latest_commit_sha":null,"homepage":"https://dev.to/karenpayneoregon/sql-server-computed-columns-with-ef-core-3h8d","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,"zenodo":null}},"created_at":"2022-12-18T23:11:03.000Z","updated_at":"2024-08-28T11:29:22.000Z","dependencies_parsed_at":null,"dependency_job_id":"5ec3e372-ddc2-435c-a095-18f1db604375","html_url":"https://github.com/karenpayneoregon/sql-server-computed-columns","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/karenpayneoregon/sql-server-computed-columns","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fsql-server-computed-columns","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fsql-server-computed-columns/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fsql-server-computed-columns/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fsql-server-computed-columns/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/karenpayneoregon","download_url":"https://codeload.github.com/karenpayneoregon/sql-server-computed-columns/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fsql-server-computed-columns/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30209941,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-07T05:23:27.321Z","status":"ssl_error","status_checked_at":"2026-03-07T05:00:17.256Z","response_time":53,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["computed-columns","csharp","csharp-core","efcore7"],"created_at":"2024-11-30T19:19:36.555Z","updated_at":"2026-03-07T08:33:12.376Z","avatar_url":"https://github.com/karenpayneoregon.png","language":"C#","readme":"# SQL-Server: Computed columns\n\n![title](assets/ArticleTitle.png)\n\n## What is a Computed Column?\n\nA [Computed Column](https://learn.microsoft.com/en-us/sql/relational-databases/tables/specify-computed-columns-in-a-table?view=sql-server-ver16) is a column whose values are derived or computed by an expression. The expression might be a constant, function or combination of values from one or more columns in the same table. \n\nThe code samples provided are based on an expressions with emphasis for [EF Core](https://learn.microsoft.com/en-us/ef/core/) while provides a data provider sample also.\n\n\nSample from code samples to get a year from the column BirthYear.\n\n![Screen1](assets/screen1.png)\n\n## Limitations and Restrictions\n\n*Microsoft* [docs](https://learn.microsoft.com/en-us/sql/relational-databases/tables/specify-computed-columns-in-a-table?view=sql-server-ver16#Limitations):\n\n- A computed column cannot be used as a DEFAULT or FOREIGN KEY constraint definition or with a NOT NULL constraint definition. However, if the computed column value is defined by a deterministic expression and the data type of the result is allowed in index columns, a computed column can be used as a key column in an index or as part of any PRIMARY KEY or UNIQUE constraint. For example, if the table has integer columns a and b, the computed column a + b may be indexed, but computed column a + DATEPART(dd, GETDATE()) cannot be indexed, because the value might change in subsequent invocations.\n- A computed column cannot be the target of an INSERT or UPDATE statement.\n- `SET QUOTED_IDENTIFIER` must be ON when you are creating or changing indexes on computed columns or indexed views. For more information, see [SET QUOTED_IDENTIFIER](https://learn.microsoft.com/en-us/sql/t-sql/statements/set-quoted-identifier-transact-sql?view=sql-server-ver16) (Transact-SQL).\n\n\n\u003e **Note**\n\u003e When a formula combines two expressions of different data types, the rules for data type precedence specify that the data type with the lower precedence is converted to the data type with the higher precedence. If the conversion is not a supported implicit conversion, the error **Error validating the formula for column column_name.** is returned. Use the CAST or CONVERT function to resolve the data type conflict. \n\n## Add a new computed column\n\n*Microsoft* SSMS [docs](https://learn.microsoft.com/en-us/sql/relational-databases/tables/specify-computed-columns-in-a-table?view=sql-server-ver16#SSMSProcedure) using [SSMS](https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver16) (SQL-Server Management Studio)\n\n\n**Note** this can be done with EF Core also. Given the following model\n\n```csharp\npublic partial class Contact\n{\n    public int Id { get; set; }\n    public string FirstName { get; set; }\n    public string LastName { get; set; }\n    public DateTime? BirthDate { get; set; }\n    public int? YearsOld { get; set; }\n    public string FullName { get; set; }\n    public int? BirthYear { get; set; }\n}\n```\n\nConfiguration for the model, see project [Context](EntityFrameworkCore/Data/Context.cs) `OnModelCreating`.\n\n\n```csharp\nprotected override void OnModelCreating(ModelBuilder modelBuilder)\n{\n    modelBuilder.Entity\u003cContact\u003e(entity =\u003e\n    {\n        entity.Property(e =\u003e e.BirthDate)\n            .HasColumnType(\"date\");\n        entity.Property(e =\u003e e.BirthYear)\n            .HasComment(\"Computes birth year from BirthDate\")\n            .HasComputedColumnSql(\"(datepart(year,[BirthDate]))\", false);\n        entity.Property(e =\u003e e.FullName)\n            .HasComputedColumnSql(\"(([FirstName]+' ')+[LastName])\", false);\n        entity.Property(e =\u003e e.YearsOld)\n            .HasComment(\"Computes years old from BirthDate\")\n            .HasComputedColumnSql(\"(datediff(year,[BirthDate],getdate()))\", false);\n    });\n\n    OnModelCreatingPartial(modelBuilder);\n}\n```\n\nHere is what the raw definition looks like in SSMS.\n\n![Schema](assets/schema.png)\n\n## EF Core reading data from Contacts\n\nFirst example reads all contacts while the second example asserts for contacts ready for retirement using the computed column YearsOld. Both examples display FirstName and LastName using the computed column FullName.\n\n```csharp\nprivate static void AllContacts()\n{\n    using var context = new Context();\n    var contacts = context.Contact.ToList();\n    foreach (Contact item in contacts)\n    {\n        Console.WriteLine($\"{item.Id,-3}{item.FullName,-15}Is {item.YearsOld,-3}years old born {item.BirthYear}\");\n    }\n\n    Console.WriteLine();\n}\nprivate static void ReadForRetirement()\n{\n    using var context = new Context();\n    int yearsOld = 65;\n\n    var readyForRetirement = context.Contact.Where(contact =\u003e contact.YearsOld \u003e yearsOld).ToList();\n\n    foreach (Contact item in readyForRetirement)\n    {\n        Console.WriteLine($\"{item.Id,-3}{item.FullName,-15}Is {item.YearsOld,-3}years old born {item.BirthYear}\");\n    }\n        \n    Console.WriteLine();\n}\n```\n\nSuppose a user interface displays `FullName`, we can use the computed column FullName to find the contact.\n\n```csharp\nprivate static void FindByFullName()\n{\n    var fullName = \"Karen Payne\";\n    using var context = new Context();\n    var contact = context.Contact.FirstOrDefault(item =\u003e item.FullName == fullName);\n    Console.WriteLine(contact.Id);\n    Console.WriteLine();\n}\n```\n\n## EF Core working with Version class\n\nComputed columns are very powerful. Entity Framework Core with its fluent API allows them to be easily added. Before using computed columns in production databases run test in SSMS on larger datasets than you would normally run, determine if performance is acceptable along with testing with proper indices.\n\n\nThis code sample shows storing version information in a SQL-Server database table.\n\nSince each part of the version are stored as int you can take those column values and create a [Version](https://learn.microsoft.com/en-us/dotnet/api/system.version?view=net-7.0) object or use `TheVersion` column for display purposes.\n\nTable definition\n\n![1](EntityFrameworkCore2/assets/figure2.png)\n\n![2](EntityFrameworkCore2/assets/Figure1.png)\n\n![3](EntityFrameworkCore2/assets/figure3.png)\n\n\n### Incrementing version parts\n\nTo keep code clean we have extension methods in a class project.\n\n```csharp\npublic static class Extensions\n{\n    public static Version IncrementMajor(this Version sender, int increment = 1) \n        =\u003e new(sender.Major + increment, sender.Minor, sender.Build, sender.Revision);\n\n    public static Version IncrementMinor(this Version sender, int increment = 1) \n        =\u003e new (sender.Major, sender.Minor + increment, sender.Build, sender.Revision);\n\n    public static Version IncrementBuild(this Version sender, int increment = 1) \n        =\u003e new (sender.Major, sender.Minor, sender.Build + increment, sender.Revision);\n\n    public static Version IncrementRevision(this Version sender, int increment = 1) \n        =\u003e new (sender.Major, sender.Minor, sender.Build, sender.Revision + increment);\n}\n```\n\nGet a record\n\n```csharp\nusing var context = new Context();\nApplicationSettings firstApp = context.ApplicationSettings.FirstOrDefault();\nVersion version = new Version(firstApp!.TheVersion);\n```\n\nIncrement a part\n\n```csharp\nversion = version.IncrementMajor(1);\nfirstApp.VersionMajor = version.Major;\n```\n\n## Simple math example\n\nIn this example we are summing up `UnitPrice` \u003ckbd\u003e*\u003c/kbd\u003e `Quantity` into computed column `RowTotal`\n\n![row](assets/totalRow.png)\n\n```csharp\npublic partial class OrderDetailsConfiguration : \n    IEntityTypeConfiguration\u003cOrderDetails\u003e\n{\n    public void Configure(EntityTypeBuilder\u003cOrderDetails\u003e entity)\n    {\n        entity.HasKey(e =\u003e e.OrderId);\n\n        entity.Property(e =\u003e e.RowTotal)\n            .HasComputedColumnSql(\"([Quantity]*[UnitPrice])\", false)\n            .HasColumnType(\"numeric(29, 2)\");\n        entity.Property(e =\u003e e.UnitPrice).HasColumnType(\"numeric(18, 2)\");\n\n        entity.HasOne(d =\u003e d.Product)\n            .WithMany(p =\u003e p.OrderDetails)\n            .HasForeignKey(d =\u003e d.ProductId)\n            .OnDelete(DeleteBehavior.ClientSetNull)\n            .HasConstraintName(\"FK_OrderDetails_Products\");\n\n        OnConfigurePartial(entity);\n    }\n\n    partial void OnConfigurePartial(EntityTypeBuilder\u003cOrderDetails\u003e entity);\n}\n```\n\n\n## See also\n\n- EF Core [Computed columns](https://learn.microsoft.com/en-us/ef/core/modeling/generated-properties?tabs=data-annotations#computed-columns)\n- [FORMAT is a convenient but expensive SQL Server function](https://www.mssqltips.com/sqlservertip/7145/sql-date-format-comparison-computed-column-materialized-column/)\n\n## Required\n\nMicrosoft Visual Studio 2022 version 17.4 or higher\n\n## NuGet packages\n\n- [ConfigurationLibrary](https://www.nuget.org/packages/ConfigurationLibrary/) is used for obtaining connection strings from `appsettings` in both projects. This is a great solution when not using dependency injection.\n- [Spectre.Console](https://www.nuget.org/packages/Spectre.Console/0.45.1-preview.0.47) for enhanced console writting.\n\n## Computed Column Performance in SQL Server\n\nIn many cases, non-persistent computed columns put too much burden on the processor, resulting in slower queries and unresponsive applications. Fortunately, SQL Server provides several strategies for improving computed column performance. You can create persisted computed columns, index the computed columns, or do both.\n\n:eyeglasses:  [Continue reading](https://www.red-gate.com/simple-talk/databases/sql-server/performance-sql-server/computed-column-performance-in-sql-server/)...\n\n## You also might like\n\n- [EF Core 7 code sample](https://github.com/karenpayneoregon/ef-core-7-samples)\n- [SQL-Server: Exploration of datetime2(7) precision](https://github.com/karenpayneoregon/sql-server-datetime2)\n- [EF Core: Working with TimeOnly](https://github.com/karenpayneoregon/ef-core-dateonly-timeonly)\n- [Storing passwords in SQL-Server database](https://dev.to/karenpayneoregon/passwords-in-sql-server-c-1fhf)\n- [Learn DateOnly \u0026 TimeOnly](https://dev.to/karenpayneoregon/learn-dateonly-timeonly-23j0)\n\n\n\n## Summary\n\nThis repository contents provide working code samples focused on using computed columns with EF Core and for those using a data provider [System.Data.SqlClient](https://www.nuget.org/packages/System.Data.SqlClient) for instance computed columns work too.\n\n:small_blue_diamond: Not all possiblities are presented, code sample have been kept simple for the sake of easy learning.","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkarenpayneoregon%2Fsql-server-computed-columns","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkarenpayneoregon%2Fsql-server-computed-columns","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkarenpayneoregon%2Fsql-server-computed-columns/lists"}