{"id":19100885,"url":"https://github.com/fdonnet/dapper-sql-generator","last_synced_at":"2025-02-27T20:56:45.533Z","repository":{"id":38001806,"uuid":"177100126","full_name":"fdonnet/dapper-sql-generator","owner":"fdonnet","description":"Tool that uses a MS-SQL project (.dacpac) to generate stored procedures, entities and Dapper DbContext (async, ready for .Net Core .Net 6)... Extensible to a lot of use cases.","archived":false,"fork":false,"pushed_at":"2023-06-14T17:10:01.000Z","size":497,"stargazers_count":25,"open_issues_count":1,"forks_count":4,"subscribers_count":5,"default_branch":"master","last_synced_at":"2024-11-09T03:55:43.446Z","etag":null,"topics":["configurator","dal","dapac","dapper","dapper-donet-core","data","generator","mssql","net6","stored-procedures"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fdonnet.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-03-22T08:21:17.000Z","updated_at":"2024-08-31T07:14:36.000Z","dependencies_parsed_at":"2023-01-21T18:46:55.036Z","dependency_job_id":null,"html_url":"https://github.com/fdonnet/dapper-sql-generator","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fdonnet%2Fdapper-sql-generator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fdonnet%2Fdapper-sql-generator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fdonnet%2Fdapper-sql-generator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fdonnet%2Fdapper-sql-generator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fdonnet","download_url":"https://codeload.github.com/fdonnet/dapper-sql-generator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241059384,"owners_count":19902371,"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":["configurator","dal","dapac","dapper","dapper-donet-core","data","generator","mssql","net6","stored-procedures"],"created_at":"2024-11-09T03:53:02.719Z","updated_at":"2025-02-27T20:56:45.526Z","avatar_url":"https://github.com/fdonnet.png","language":"C#","readme":"For MySql or to see the new version i m working on, go =\u003e https://github.com/fdonnet/Dapper-Layers-Generator (Console app, multi db provider) \n\n# MSSQL - Dapper generator\nA simple and not too ambitious tool that helps you to generate some important generic layers for your MSSQL - C# (netcore) - Dapper project. \n\nIt's extensible and modifiable. \n\nIf you create your own generators an generator-settings, share your results via a pull request, we will be very happy to integrate it. Don't hesitate to enhance the quality of our coding, some parts are very \"quick and dirty\" stuff.\n\nWe dev this tool to help us in a real project. So it will help us for sure but we cannot guarantee it will help you...\n## Goals\nUse your Visual Studio Database Project (SSDT) to generate boring stuff to code. (good tables definition =\u003e good generation)\n\n**Based on your tables definition and your generator configuration:**\n- Generate standard stored procedures\n- Generate base C# entities\n- Generate base data access layer\n\n## Limitations\nA lot....... (but you can help!)\n- Only works with SqlServer DB and ~Visual Studio Database Project. The generator uses a .dacpac file as the model entry point to eat the tables definition. (your tables and fields need to be in lowercase and with _ to separate words (table: user_role, field: has_access will be transformed in C# in PascalCase, UserRole and HasAccess)...\n- You need to be on Windows to use the UI (WPF prj). Sorry for that guys. If you are on other systems, you can convert the logic layer and inject a JSON config file to the generator. It will work.\n- The C# entities generator suits our needs. We let you see if it will suit yours.\n- The C# repo generator targets **.netcore Dapper(async)** (ex: DAL layer for webapi netcore project) and it doesn't integrate a\"repository\" pattern. That's a choice... but you can change it or create a new generator for this part.\n- No \"get entity with children\" function (maybe if we will have more time, or if someone want to help). We know how to do it but it's not a small job to automate it.\n\n## Generate\n![Alt text](/img/output.png?raw=true \"Generate output\")\n- For TSQL stored procedures, select a folder in your Visual Studio Database tool (SSDT) project. You will be able to use the \"compare tool\" to update your database with the generated SPs.\n- For C# entities, select the folder in your target project where are located your entities. (include the generated file in your Visual Studio solution)\n- For C# repo, select a folder where is located your target DAL layer. (include the generated file in your Visual Studio solution)\n\n## Generators (settings)\nFirst step (load your .dacpac file)\n![Alt text](/img/load.PNG?raw=true \"Load your model\")\n\nAfter that, you can define your settings at a global level (all tables) or override for each table level in the \"Table generation settings\" (right pan, near preview tab):\n![Alt text](/img/settings.png?raw=true \"Settings\")\n\nSome specific settings are only available at the \"Table level\". \nWe let you discover !\n\nWhen you are happy with your model settings, don't forget to save your config:\n![Alt text](/img/save_config.png?raw=true \"Save your config\")\n\nIt will save all the defined settings in a JSON file and you will be able to load it when your base model has been changed. (ex: new settings for new tables without loosing your old configuration)\n\n## TSQL stored procedures generator\nIn \"General\" tab, you can select what types of SP you want o generate.\n\nAt global and table level you can specify:\n\n![Alt text](/img/sqlsettings.png?raw=true \"Stored proc settings\")\n- The roles you want to grant \"EXECUTE\" on the SP (the roles need to be defined in your model .dacpac file).\n- For some SP types, you have the possibility to directly exclude some fields.\n- For \"select by UK\" generator, you need to specify unique constrain(s) in your sql table definition.\n\n## C# Entities generator\nIn the \"General\" tab:\n\n![Alt text](/img/entitiesglobal.png?raw=true \"Entities settings\")\n\n*(All this settings, can be defined at the global level or can be overrided at the table lvl config)*\n\n- Define a namespace \n- Implement interface(s) in the generated entity\n- Implement ICloneable (with a minimal .Clone() template function)\n- Set some standards decorators\n\nAt the table lvl settings, you can:\n\n- Define a custom type (ex: if you have enum fields) or custom decorator for each table column:\n![Alt text](/img/entitiesfieldtype.png?raw=true \"Field type settings\") ![Alt text](/img/entitiescustomdeco.png?raw=true \"Decorators settings\")\n\n## C# Repo/DAL generator\nIt will generate ONE simple DBContext (interface + class) and a repo/dal class for each table (+interface).\n\nThe repo/dal for each table **will be defined as \"partial\"**. =\u003e You will be able to extend your functionnalities outside of the generated files (via a new file for the interface or the class definition).\n\nIn the settings, you can define the connection string **name** that will be injected via netcore IConfiguration object in the DbContext settings:\n\n![Alt text](/img/repoconstring.png?raw=true \"Connection name\")\n\n! **It's the connection name, not the connection string...** !\n\nDbContext constructor:\n\n```csharp\npublic DbContext(IConfiguration config)\n {\n     _config = config;\n     DefaultTypeMap.MatchNamesWithUnderscores = true;\n     _cn = new SqlConnection(_config.GetConnectionString(\"Default\"));\n }\n```\n \n### No Repository pattern =\u003e only a simple DAL you can extend\n\n*Biased approach... maybe it will not fit your needs....*\n\nOnly available, for the moment\" with Dapper async implementation...\n\nIn netcore, see some implementations bellow if you have a service layer, and an api layer (controller):\n\n- Inject your DbContext in the service constructor (**tips: you can choose the name you want in the generator for your DbContext class**) . \n\n*You can see we have injected the IConfiguration too...*\n\n```csharp\n private readonly ILogger\u003cServiceTest\u003e _log;\n private readonly IConfiguration _config;\n private readonly IDbContext _context;\n \n public ServiceTest(ILogger\u003cApplicationManager\u003e logger, IConfiguration config, \n    IDbContext context)\n {\n     _log = logger;\n     _config = config;\n     _context = context;\n }\n```\n\nIn your controller, inject your service ServiceTest:\n```csharp\nprivate readonly ILogger\u003cMyController\u003e _log;\nprivate readonly IConfiguration _config;\nprivate readonly IServiceTest _serviceTest;\n\npublic MyController(ILogger\u003cMyController\u003e logger, IConfiguration config,\n    IServiceTest serviceTest)\n\n{\n    _log = logger;\n    _config = config;\n    _serviceTest = serviceTest;\n}\n```\n\nIn your netcore startup / configure services function:\n- Add your dbcontext as transient/scoped\n- And your services as transient/scoped\n```csharp\nservices.AddTransient\u003cIDbContext, DbContext\u003e();\n\nservices.AddScoped\u003cIServiceTest, ServiceTest\u003e();\n```\n\nnetcore, so good! Your DbContext will be injected automatically via your service injection in the controller.\nYou will be able to use your DAL in your service layer (the DbContext will be able to call all the repo/dal you have defined).\n\nReminder: You can extend your interface and repo class via another \"partial\" file. It allows you to re-generate your base definition via the tool anytime.\n\n#### And if I need a transaction between repos ?\nFrom a method of your service/core layer:\n\nThe using statement is not really needed but it protects you from yourself;\n```csharp\n//Open a transaction\n using(var trans = await _dbContext.OpenTransaction())\n {\n    //Execute operations example\n    var resultDel = await _dbContext.PermissionRepo.DeleteRoles(permissionId);\n    bool ok = await _dbContext.RolePermissionRepo.InsertByLinkedIds(linkedIds, currentUserId, DateTime.Now);\n\n    //Commit transaction\n    _dbContext.CommitTransaction();\n }\n```\n\nAsync transaction is a big debate. We choose to not use the .net transaction (TransactionScopeAsyncFlowOption) because we dont' really understand how it is working behind. We prefer to use a standard IDBTransaction, because we think it's finally not too bad... but you could convince us...\n\n#### And if I need more control on my DBContext lifecycle ?\nIn case of parallel jobs (Tasks) or if you use the DAL in a NON Web/Web Api scope... the lifetime of our Dbcontexts needs to be more managed.\nThe generator implements a very minimalistic DBContextFactory. So you can inject the IDBContextFactory in your services constructor and keep the control :\n```csharp\n//Parallel 2 tasks jobs (thread safe)\nTask\u003cIEnumerable\u003cObject1\u003e\u003e object1Task;\nTask\u003cIEnumerable\u003cObject2\u003e\u003e object2Task;\n\n//Job1\nusing var dbContext1 = _dbContextFactory.Create();\nobject1Task = dbContext1.object1Repo.GetAll();\n\n//Job2\nusing var dbContext2 = _dbContextFactory.Create();\nobject2Task = dbContext2.object2Repo.GetAll();\n\n//Wait for jobs finished and retrieve the result\n// Don't close the Dbcontexts before Task.WhenAll\nawait Task.WhenAll(object1Task, object2Task);\nvar object1List = await object1Task;\nvar object2List = await object2Task;\n```\nSee above : 2 separate DB contexts to open 2 parallel db connections..\n\n\n\n","funding_links":[],"categories":["others"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffdonnet%2Fdapper-sql-generator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffdonnet%2Fdapper-sql-generator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffdonnet%2Fdapper-sql-generator/lists"}