{"id":21623026,"url":"https://github.com/pandatecham/be-lib-efcore-postgres-extensions","last_synced_at":"2025-09-08T09:39:37.536Z","repository":{"id":230390295,"uuid":"779245437","full_name":"PandaTechAM/be-lib-efcore-postgres-extensions","owner":"PandaTechAM","description":"Extend EF Core's capabilities with PostgreSQL-specific features like ForUpdate locking syntax and more, seamlessly integrating into your development workflow.","archived":false,"fork":false,"pushed_at":"2025-08-07T17:23:59.000Z","size":204,"stargazers_count":7,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"development","last_synced_at":"2025-08-07T17:59:49.216Z","etag":null,"topics":["bulk-insert","ef-core","for-update","library","lock","npgsql","pandatech","postgres-copy","postgresql"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PandaTechAM.png","metadata":{"files":{"readme":"Readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","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,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2024-03-29T11:28:32.000Z","updated_at":"2025-08-07T17:23:06.000Z","dependencies_parsed_at":"2024-07-18T00:17:01.365Z","dependency_job_id":"5defc5e4-ccc1-4cdb-b695-7a7a8c568858","html_url":"https://github.com/PandaTechAM/be-lib-efcore-postgres-extensions","commit_stats":null,"previous_names":["pandatecham/be-lib-efcore-postgres-extensions"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/PandaTechAM/be-lib-efcore-postgres-extensions","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PandaTechAM%2Fbe-lib-efcore-postgres-extensions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PandaTechAM%2Fbe-lib-efcore-postgres-extensions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PandaTechAM%2Fbe-lib-efcore-postgres-extensions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PandaTechAM%2Fbe-lib-efcore-postgres-extensions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PandaTechAM","download_url":"https://codeload.github.com/PandaTechAM/be-lib-efcore-postgres-extensions/tar.gz/refs/heads/development","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PandaTechAM%2Fbe-lib-efcore-postgres-extensions/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274166448,"owners_count":25233955,"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","status":"online","status_checked_at":"2025-09-08T02:00:09.813Z","response_time":121,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":["bulk-insert","ef-core","for-update","library","lock","npgsql","pandatech","postgres-copy","postgresql"],"created_at":"2024-11-25T00:11:18.259Z","updated_at":"2025-09-08T09:39:37.525Z","avatar_url":"https://github.com/PandaTechAM.png","language":"C#","readme":"# Pandatech.EFCore.PostgresExtensions\n\nPandatech.EFCore.PostgresExtensions is an advanced NuGet package designed to enhance PostgreSQL functionalities within\nEntity Framework Core, leveraging specific features not covered by the official Npgsql.EntityFrameworkCore.PostgreSQL\npackage. This package introduces optimized row-level locking mechanisms and PostgreSQL sequence random incrementing\nfeatures.\n\n## Features\n\n1. **Row-Level Locking**: Implements the PostgreSQL `FOR UPDATE` feature, providing three lock\n   behaviors - `Wait`, `Skip`, and\n   `NoWait`, to facilitate advanced transaction control and concurrency management.\n2. **Random Incrementing Sequence Generation:** Provides a secure way to generate sequential IDs with random increments\n   to prevent predictability and potential data exposure. This ensures IDs are non-sequential and non-predictable,\n   enhancing security and balancing database load.\n3. **Natural Sorting**: Provides way to calculate natural sort compliant order for string, which can be used\n   in `ORDER BY` clause. This is useful for sorting strings that contain numbers in a human-friendly way.\n4. **Schema Rollback Helpers**: Extension methods `DropRandomIdSequence` and `DropNaturalSortKeyFunction` simplify\n   cleanup in `Down` migrations.\n\n## Installation\n\nTo install Pandatech.EFCore.PostgresExtensions, use the following NuGet command:\n\n```bash\nInstall-Package Pandatech.EFCore.PostgresExtensions\n```\n\n## Usage\n\n### Row-Level Locking\n\nConfigure your DbContext to use Npgsql and enable query locks:\n\n```csharp\nservices.AddDbContext\u003cMyDbContext\u003e(options =\u003e\n{\n    options.UseNpgsql(Configuration.GetConnectionString(\"MyDatabaseConnection\"))\n           .UseQueryLocks();\n});\n```\n\nWithin a transaction scope, apply the desired lock behavior using the `ForUpdate` extension method:\n\n```csharp\nusing var transaction = _dbContext.Database.BeginTransaction();\ntry\n{\n    var entityToUpdate = _dbContext.Entities\n        .Where(e =\u003e e.Id == id)\n        .ForUpdate(LockBehavior.NoWait) // Or use LockBehavior.Default (Wait)/ LockBehavior.SkipLocked\n        .FirstOrDefault();\n\n    // Perform updates on entityToUpdate\n    await _dbContext.SaveChangesAsync();\n    transaction.Commit();\n}\ncatch (Exception ex)\n{\n    transaction.Rollback();\n    // Handle exception\n}\n```\n\n### Random Incrementing Sequence Generation\n\nTo configure a model to use the random ID sequence, use the `HasRandomIdSequence` extension method in your entity\nconfiguration:\n\n```csharp\npublic class Animal\n{\n    public long Id { get; set; }\n    public string Name { get; set; }\n}\n\npublic class AnimalEntityConfiguration : IEntityTypeConfiguration\u003cAnimal\u003e\n{\n    public void Configure(EntityTypeBuilder\u003cAnimal\u003e builder)\n    {\n        builder.HasKey(x =\u003e x.Id);\n        builder.Property(x =\u003e x.Id)\n               .HasRandomIdSequence();\n    }\n}\n```\n\nAfter creating a migration, add the custom function **above create table** script in your migration class:\n\n```csharp\npublic partial class PgFunction : Migration\n{\n    /// \u003cinheritdoc /\u003e\n    protected override void Up(MigrationBuilder migrationBuilder)\n    {\n        migrationBuilder.CreateRandomIdSequence(\"animal\", \"id\", 5, 5, 10); //Add this line manually\n        \n        migrationBuilder.CreateTable(\n            name: \"animal\",\n            columns: table =\u003e new\n            {\n                id = table.Column\u003clong\u003e(type: \"bigint\", nullable: false, defaultValueSql: \"animal_random_id_generator()\"),\n                name = table.Column\u003cstring\u003e(type: \"text\", nullable: false)\n            },\n            constraints: table =\u003e\n            {\n                table.PrimaryKey(\"pk_animal\", x =\u003e x.id);\n            });\n    }\n\n    /// \u003cinheritdoc /\u003e\n    protected override void Down(MigrationBuilder migrationBuilder)\n    {\n        migrationBuilder.DropRandomIdSequence(\"animal\", \"id\");\n         \n        migrationBuilder.DropTable(\n            name: \"animal\");\n    }\n}\n```\n\n#### Additional notes\n\n- The random incrementing sequence feature ensures the generated IDs are unique, non-sequential, and non-predictable,\n  enhancing security.\n- The feature supports only `long` data type (`bigint` in PostgreSQL).\n\n### Natural Sort Key\n\nThis package can generate a natural sort key for your text columns—especially useful when sorting addresses or other\nfields that contain embedded numbers. It avoids plain lexicographic ordering (e.g. `\"10\"` \u003c `\"2\"`) by treating numeric\nsubstrings numerically.\n\n#### How to Use\n\n1. Create the function in your migration (once per database). Call the helper method in `Up()`:\n    ```csharp\n       public partial class AddNaturalSortKeyToBuildings : Migration\n    {\n        protected override void Up(MigrationBuilder migrationBuilder)\n        {\n        // Create the natural sort key function in PostgreSQL\n        migrationBuilder.CreateNaturalSortKeyFunction();   \n           \n        protected override void Down(MigrationBuilder migrationBuilder)\n           {\n               migrationBuilder.DropNaturalSortKeyFunction();        \n           }\n        }\n    }\n    ```\n2. Configure your entity to use the natural sort key. In your `IEntityTypeConfiguration` for the table:\n    ```csharp\n    public class BuildingConfiguration : IEntityTypeConfiguration\u003cBuilding\u003e\n    {\n        public void Configure(EntityTypeBuilder\u003cBuilding\u003e builder)\n        {\n            // Create a computed column in EF (like \"address_natural_sort_key\")\n            builder\n                .Property(x =\u003e x.AddressNaturalSortKey)\n                .HasNaturalSortKey(\"address\"); // Points to the column storing your original address\n        }\n    }    \n    ```\n\nWhen you query the entity, simply `ORDER BY AddressNaturalSortKey` to get true “natural” ordering in PostgreSQL.\n\n## License\n\nPandatech.EFCore.PostgresExtensions is licensed under the MIT License.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpandatecham%2Fbe-lib-efcore-postgres-extensions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpandatecham%2Fbe-lib-efcore-postgres-extensions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpandatecham%2Fbe-lib-efcore-postgres-extensions/lists"}