#codeefficiency — Public Fediverse posts
Live and recent posts from across the Fediverse tagged #codeefficiency, aggregated by home.social.
-
Forget Flags and Scripts: Just Rename the File
https://robertsdotpm.github.io/software_engineering/program_names_as_input.html
#HackerNews #ForgetFlagsAndScripts #RenameFile #SoftwareEngineering #CodeEfficiency #ProgrammingTips
-
Forget Flags and Scripts: Just Rename the File
https://robertsdotpm.github.io/software_engineering/program_names_as_input.html
#HackerNews #ForgetFlagsAndScripts #RenameFile #SoftwareEngineering #CodeEfficiency #ProgrammingTips
-
Forget Flags and Scripts: Just Rename the File
https://robertsdotpm.github.io/software_engineering/program_names_as_input.html
#HackerNews #ForgetFlagsAndScripts #RenameFile #SoftwareEngineering #CodeEfficiency #ProgrammingTips
-
Forget Flags and Scripts: Just Rename the File
https://robertsdotpm.github.io/software_engineering/program_names_as_input.html
#HackerNews #ForgetFlagsAndScripts #RenameFile #SoftwareEngineering #CodeEfficiency #ProgrammingTips
-
Forget Flags and Scripts: Just Rename the File
https://robertsdotpm.github.io/software_engineering/program_names_as_input.html
#HackerNews #ForgetFlagsAndScripts #RenameFile #SoftwareEngineering #CodeEfficiency #ProgrammingTips
-
👨💻 Oh, joy! Another tool to remind you of how much money you're burning on your glorified code monkey, Claude 🐒. Because who doesn't want to track their AI's "cache efficiency" while it slowly drains your budget in real-time? 💸 Maybe by the end, you'll even get a trophy for the money you've saved (or not)! 🏆
https://github.com/liorwn/claudetop #AItools #BudgetTracking #CodeEfficiency #TechHumor #MoneyManagement #HackerNews #ngated -
👨💻 Oh, joy! Another tool to remind you of how much money you're burning on your glorified code monkey, Claude 🐒. Because who doesn't want to track their AI's "cache efficiency" while it slowly drains your budget in real-time? 💸 Maybe by the end, you'll even get a trophy for the money you've saved (or not)! 🏆
https://github.com/liorwn/claudetop #AItools #BudgetTracking #CodeEfficiency #TechHumor #MoneyManagement #HackerNews #ngated -
👨💻 Oh, joy! Another tool to remind you of how much money you're burning on your glorified code monkey, Claude 🐒. Because who doesn't want to track their AI's "cache efficiency" while it slowly drains your budget in real-time? 💸 Maybe by the end, you'll even get a trophy for the money you've saved (or not)! 🏆
https://github.com/liorwn/claudetop #AItools #BudgetTracking #CodeEfficiency #TechHumor #MoneyManagement #HackerNews #ngated -
👨💻 Oh, joy! Another tool to remind you of how much money you're burning on your glorified code monkey, Claude 🐒. Because who doesn't want to track their AI's "cache efficiency" while it slowly drains your budget in real-time? 💸 Maybe by the end, you'll even get a trophy for the money you've saved (or not)! 🏆
https://github.com/liorwn/claudetop #AItools #BudgetTracking #CodeEfficiency #TechHumor #MoneyManagement #HackerNews #ngated -
Интерфейсы риелторских платформ: почему все сложно и как это исправить
Всем привет! Разработка интерфейса платформы для риелторов — задачка нетривиальная. В этой статье я расскажу о том, как мы делаем наш интерфейс понятным и дружелюбным.
https://habr.com/ru/articles/1007968/
#performanceoptimization #codeefficiency #profilingtools #profiling #algorithms #algorithmanalysis
-
Интерфейсы риелторских платформ: почему все сложно и как это исправить
Всем привет! Разработка интерфейса платформы для риелторов — задачка нетривиальная. В этой статье я расскажу о том, как мы делаем наш интерфейс понятным и дружелюбным.
https://habr.com/ru/articles/1007968/
#performanceoptimization #codeefficiency #profilingtools #profiling #algorithms #algorithmanalysis
-
Интерфейсы риелторских платформ: почему все сложно и как это исправить
Всем привет! Разработка интерфейса платформы для риелторов — задачка нетривиальная. В этой статье я расскажу о том, как мы делаем наш интерфейс понятным и дружелюбным.
https://habr.com/ru/articles/1007968/
#performanceoptimization #codeefficiency #profilingtools #profiling #algorithms #algorithmanalysis
-
Интерфейсы риелторских платформ: почему все сложно и как это исправить
Всем привет! Разработка интерфейса платформы для риелторов — задачка нетривиальная. В этой статье я расскажу о том, как мы делаем наш интерфейс понятным и дружелюбным.
https://habr.com/ru/articles/1007968/
#performanceoptimization #codeefficiency #profilingtools #profiling #algorithms #algorithmanalysis
-
Интерфейсы риелторских платформ: почему все сложно и как это исправить
Разработка интерфейсов специализированных сервисов — дело непростое. Особенно остро эта задача встает перед разработчиками риелторских онлайн-платформ, где взаимодействие пользователей тесно связано с огромным количеством данных, специфической терминологией и разными уровнями восприятия. Меня зовут Никита Осадчий, я менеджер продукта в Нмаркет.ПРО. В этой статье я расскажу о том, как мы оптимизируем интерфейс и делаем его дружелюбным и понятным любому агенту по недвижимости.
https://habr.com/ru/articles/1004408/
#performanceoptimization #codeefficiency #profilingtools #profiling #algorithms #algorithmanalysis
-
Интерфейсы риелторских платформ: почему все сложно и как это исправить
Разработка интерфейсов специализированных сервисов — дело непростое. Особенно остро эта задача встает перед разработчиками риелторских онлайн-платформ, где взаимодействие пользователей тесно связано с огромным количеством данных, специфической терминологией и разными уровнями восприятия. Меня зовут Никита Осадчий, я менеджер продукта в Нмаркет.ПРО. В этой статье я расскажу о том, как мы оптимизируем интерфейс и делаем его дружелюбным и понятным любому агенту по недвижимости.
https://habr.com/ru/articles/1004408/
#performanceoptimization #codeefficiency #profilingtools #profiling #algorithms #algorithmanalysis
-
Интерфейсы риелторских платформ: почему все сложно и как это исправить
Разработка интерфейсов специализированных сервисов — дело непростое. Особенно остро эта задача встает перед разработчиками риелторских онлайн-платформ, где взаимодействие пользователей тесно связано с огромным количеством данных, специфической терминологией и разными уровнями восприятия. Меня зовут Никита Осадчий, я менеджер продукта в Нмаркет.ПРО. В этой статье я расскажу о том, как мы оптимизируем интерфейс и делаем его дружелюбным и понятным любому агенту по недвижимости.
https://habr.com/ru/articles/1004408/
#performanceoptimization #codeefficiency #profilingtools #profiling #algorithms #algorithmanalysis
-
Интерфейсы риелторских платформ: почему все сложно и как это исправить
Разработка интерфейсов специализированных сервисов — дело непростое. Особенно остро эта задача встает перед разработчиками риелторских онлайн-платформ, где взаимодействие пользователей тесно связано с огромным количеством данных, специфической терминологией и разными уровнями восприятия. Меня зовут Никита Осадчий, я менеджер продукта в Нмаркет.ПРО. В этой статье я расскажу о том, как мы оптимизируем интерфейс и делаем его дружелюбным и понятным любому агенту по недвижимости.
https://habr.com/ru/articles/1004408/
#performanceoptimization #codeefficiency #profilingtools #profiling #algorithms #algorithmanalysis
-
🚀✨ Wow, look at this groundbreaking feat: reinventing the wheel with an #OpenGL renderer in fewer lines than your average Twitter rant! 🙄 Because nothing screams "cutting-edge innovation" more than cramming 5,000 lines of code into a #Github repo while pretending it's a revolution. 🧑💻🔍
https://github.com/raysan5/raylib/blob/master/src/external/rlsw.h #Innovation #CodeEfficiency #TechTrends #SoftwareDevelopment #HackerNews #ngated -
🚀✨ Wow, look at this groundbreaking feat: reinventing the wheel with an #OpenGL renderer in fewer lines than your average Twitter rant! 🙄 Because nothing screams "cutting-edge innovation" more than cramming 5,000 lines of code into a #Github repo while pretending it's a revolution. 🧑💻🔍
https://github.com/raysan5/raylib/blob/master/src/external/rlsw.h #Innovation #CodeEfficiency #TechTrends #SoftwareDevelopment #HackerNews #ngated -
🚀✨ Wow, look at this groundbreaking feat: reinventing the wheel with an #OpenGL renderer in fewer lines than your average Twitter rant! 🙄 Because nothing screams "cutting-edge innovation" more than cramming 5,000 lines of code into a #Github repo while pretending it's a revolution. 🧑💻🔍
https://github.com/raysan5/raylib/blob/master/src/external/rlsw.h #Innovation #CodeEfficiency #TechTrends #SoftwareDevelopment #HackerNews #ngated -
🚀✨ Wow, look at this groundbreaking feat: reinventing the wheel with an #OpenGL renderer in fewer lines than your average Twitter rant! 🙄 Because nothing screams "cutting-edge innovation" more than cramming 5,000 lines of code into a #Github repo while pretending it's a revolution. 🧑💻🔍
https://github.com/raysan5/raylib/blob/master/src/external/rlsw.h #Innovation #CodeEfficiency #TechTrends #SoftwareDevelopment #HackerNews #ngated -
Ah, yes, the "lightweight" tool for Linux VMs—because nothing screams efficiency like adding another layer of complexity to your server management. 🤦♂️ #GitHub promises to save us all with AI magic that writes mediocre code and ensures our apps are as "intelligent" as a rock. 🎩✨ Time to revolutionize the world one bloated feature at a time! 🐢💨
https://github.com/ccheshirecat/flint #LinuxVMs #ServerManagement #AItools #CodeEfficiency #SoftwareDevelopment #HackerNews #ngated -
Ah, yes, the "lightweight" tool for Linux VMs—because nothing screams efficiency like adding another layer of complexity to your server management. 🤦♂️ #GitHub promises to save us all with AI magic that writes mediocre code and ensures our apps are as "intelligent" as a rock. 🎩✨ Time to revolutionize the world one bloated feature at a time! 🐢💨
https://github.com/ccheshirecat/flint #LinuxVMs #ServerManagement #AItools #CodeEfficiency #SoftwareDevelopment #HackerNews #ngated -
Ah, yes, the "lightweight" tool for Linux VMs—because nothing screams efficiency like adding another layer of complexity to your server management. 🤦♂️ #GitHub promises to save us all with AI magic that writes mediocre code and ensures our apps are as "intelligent" as a rock. 🎩✨ Time to revolutionize the world one bloated feature at a time! 🐢💨
https://github.com/ccheshirecat/flint #LinuxVMs #ServerManagement #AItools #CodeEfficiency #SoftwareDevelopment #HackerNews #ngated -
Ah, yes, the "lightweight" tool for Linux VMs—because nothing screams efficiency like adding another layer of complexity to your server management. 🤦♂️ #GitHub promises to save us all with AI magic that writes mediocre code and ensures our apps are as "intelligent" as a rock. 🎩✨ Time to revolutionize the world one bloated feature at a time! 🐢💨
https://github.com/ccheshirecat/flint #LinuxVMs #ServerManagement #AItools #CodeEfficiency #SoftwareDevelopment #HackerNews #ngated -
Slow builds? Messy dependencies? CI dragging you down? Learn how modern tools and techniques like containers, smart CI, and incremental #refactoring can streamline your #embedded development workflow. Read more: #CodeEfficiency #SoftwareEngineering
https://www.kdab.com/streamlining-development-by-mastering-modern-development-practices/ -
Slow builds? Messy dependencies? CI dragging you down? Learn how modern tools and techniques like containers, smart CI, and incremental #refactoring can streamline your #embedded development workflow. Read more: #CodeEfficiency #SoftwareEngineering
https://www.kdab.com/streamlining-development-by-mastering-modern-development-practices/ -
Slow builds? Messy dependencies? CI dragging you down? Learn how modern tools and techniques like containers, smart CI, and incremental #refactoring can streamline your #embedded development workflow. Read more: #CodeEfficiency #SoftwareEngineering
https://www.kdab.com/streamlining-development-by-mastering-modern-development-practices/ -
Slow builds? Messy dependencies? CI dragging you down? Learn how modern tools and techniques like containers, smart CI, and incremental #refactoring can streamline your #embedded development workflow. Read more: #CodeEfficiency #SoftwareEngineering
https://www.kdab.com/streamlining-development-by-mastering-modern-development-practices/ -
Slow builds? Messy dependencies? CI dragging you down? Learn how modern tools and techniques like containers, smart CI, and incremental #refactoring can streamline your #embedded development workflow. Read more: #CodeEfficiency #SoftwareEngineering
https://www.kdab.com/streamlining-development-by-mastering-modern-development-practices/ -
🚀🎩 Behold: a "single-header profiler" for #C++17 — because who doesn't love cramming more into one header file, ensuring that your codebase is both a tangled mess and a monument to "efficiency"? 🙈 It's on #GitHub, a site that never met a poorly structured code dump it didn't love.
https://github.com/DmitriBogdanov/UTL/blob/master/docs/module_profiler.md #singleheader #profiling #codeefficiency #tangledcode #HackerNews #ngated -
🚀🎩 Behold: a "single-header profiler" for #C++17 — because who doesn't love cramming more into one header file, ensuring that your codebase is both a tangled mess and a monument to "efficiency"? 🙈 It's on #GitHub, a site that never met a poorly structured code dump it didn't love.
https://github.com/DmitriBogdanov/UTL/blob/master/docs/module_profiler.md #singleheader #profiling #codeefficiency #tangledcode #HackerNews #ngated -
🚀🎩 Behold: a "single-header profiler" for #C++17 — because who doesn't love cramming more into one header file, ensuring that your codebase is both a tangled mess and a monument to "efficiency"? 🙈 It's on #GitHub, a site that never met a poorly structured code dump it didn't love.
https://github.com/DmitriBogdanov/UTL/blob/master/docs/module_profiler.md #singleheader #profiling #codeefficiency #tangledcode #HackerNews #ngated -
🚀🎩 Behold: a "single-header profiler" for #C++17 — because who doesn't love cramming more into one header file, ensuring that your codebase is both a tangled mess and a monument to "efficiency"? 🙈 It's on #GitHub, a site that never met a poorly structured code dump it didn't love.
https://github.com/DmitriBogdanov/UTL/blob/master/docs/module_profiler.md #singleheader #profiling #codeefficiency #tangledcode #HackerNews #ngated -
🚀✨ Two years to create a "revolutionary" #IDE that no one asked for, featuring a buffet of #buzzwords and a free token gimmick – because who wouldn't want to export their inefficiency-laden code to logs? 😂 #InnovationAtItsFinest 🍿
https://studio.codevideo.io #Innovation #CodeEfficiency #TechHumor #HackerNews #ngated -
🚀✨ Two years to create a "revolutionary" #IDE that no one asked for, featuring a buffet of #buzzwords and a free token gimmick – because who wouldn't want to export their inefficiency-laden code to logs? 😂 #InnovationAtItsFinest 🍿
https://studio.codevideo.io #Innovation #CodeEfficiency #TechHumor #HackerNews #ngated -
🚀✨ Two years to create a "revolutionary" #IDE that no one asked for, featuring a buffet of #buzzwords and a free token gimmick – because who wouldn't want to export their inefficiency-laden code to logs? 😂 #InnovationAtItsFinest 🍿
https://studio.codevideo.io #Innovation #CodeEfficiency #TechHumor #HackerNews #ngated -
🚀✨ Two years to create a "revolutionary" #IDE that no one asked for, featuring a buffet of #buzzwords and a free token gimmick – because who wouldn't want to export their inefficiency-laden code to logs? 😂 #InnovationAtItsFinest 🍿
https://studio.codevideo.io #Innovation #CodeEfficiency #TechHumor #HackerNews #ngated -
A Deep Dive into the satisfies operator in Typescript
Maina Wycliffe explores the 'satisfies' operator introduced in TypeScript 4.9, explaining its purpose, benefits, and use cases.
The article highlights how this operator allows type validation without changing the inferred type, contrasting it with type annotations and assertions. Practical examples demonstrate its advantages.
#TypeScript #TypeSafety #CodeEfficiency #Programming
https://www.allthingstypescript.dev/p/a-deep-dive-into-the-typescript-satisfies -
A Deep Dive into the satisfies operator in Typescript
Maina Wycliffe explores the 'satisfies' operator introduced in TypeScript 4.9, explaining its purpose, benefits, and use cases.
The article highlights how this operator allows type validation without changing the inferred type, contrasting it with type annotations and assertions. Practical examples demonstrate its advantages.
#TypeScript #TypeSafety #CodeEfficiency #Programming
https://www.allthingstypescript.dev/p/a-deep-dive-into-the-typescript-satisfies -
A Deep Dive into the satisfies operator in Typescript
Maina Wycliffe explores the 'satisfies' operator introduced in TypeScript 4.9, explaining its purpose, benefits, and use cases.
The article highlights how this operator allows type validation without changing the inferred type, contrasting it with type annotations and assertions. Practical examples demonstrate its advantages.
#TypeScript #TypeSafety #CodeEfficiency #Programming
https://www.allthingstypescript.dev/p/a-deep-dive-into-the-typescript-satisfies -
A Deep Dive into the satisfies operator in Typescript
Maina Wycliffe explores the 'satisfies' operator introduced in TypeScript 4.9, explaining its purpose, benefits, and use cases.
The article highlights how this operator allows type validation without changing the inferred type, contrasting it with type annotations and assertions. Practical examples demonstrate its advantages.
#TypeScript #TypeSafety #CodeEfficiency #Programming
https://www.allthingstypescript.dev/p/a-deep-dive-into-the-typescript-satisfies -
A Deep Dive into the satisfies operator in Typescript
Maina Wycliffe explores the 'satisfies' operator introduced in TypeScript 4.9, explaining its purpose, benefits, and use cases.
The article highlights how this operator allows type validation without changing the inferred type, contrasting it with type annotations and assertions. Practical examples demonstrate its advantages.
#TypeScript #TypeSafety #CodeEfficiency #Programming
https://www.allthingstypescript.dev/p/a-deep-dive-into-the-typescript-satisfies -
Generic Repository Pattern in C#
Have you ever dreaded writing the same boilerplate repository code repeatedly? You’re not alone; I will share my implementation of the Code First Generic Repository Pattern in C#. I will only include some of the code because it will make the post incredibly long. At the end of the post, I will share a Goal donation to post a Git download link so you can take it for a spin. As a bonus, the repository uses Code First and Unit of Work.
Generic Repository Pattern in C#
Let’s begin with the Entity interface. The IEntity interface is a typical pattern used in software development to define a contract for entities, typically in the context of data access and persistence. It usually includes a property for the entity’s unique identifier. The Generic Type: The IEntity interface uses a generic type parameter TKey to allow flexibility in the type of the identifier (e.g., int, Guid, string). The ID property will identify each entity uniquely. Feel free to read more about the implementation at the entity framework core generic repository and Structured Query IEntity.
public interface IEntity<TKey>{ TKey Id { get; set; }}You might find the following definition of the generic repository pattern on the interwebs.
The Generic Repository pattern in C# is a design pattern that abstracts the application’s data layer, making it easier to manage data access logic across different data sources. It aims to reduce redundancy by implementing typical data operations in a single, generic repository rather than having separate repositories for each entity type.
public interface IGenericRepository<TEntity, TKey> where TEntity : class, IEntity<TKey>{ void Delete(TEntity entityToDelete); TEntity? GetFirstOrDefault(Expression<Func<TEntity, bool>> predicate); void Update(TEntity entityToUpdate); void Save(); void Dispose();}The interface header has two generic types. TEntity is the domain class, and the TKey is the ID type, int, or string. Note that IEntity abstracts away the type TKey. It looks complex for the moment, but you will see benefits later.
Moving away from the Generic Repository, let’s focus on the pattern of the Unit of Work. According to Copilot:
The Unit of Work is a design pattern used in software development to manage and coordinate changes to a database. It ensures that all operations within a single business transaction are treated as a single unit, which means they either all succeed, or all fail together. This helps maintain data integrity and consistency.
public interface IUnitOfWork : IDisposable{ IGenericRepository<TEntity, TKey> Repository<TEntity, TKey>() where TEntity : class, IEntity<TKey>; void Save(); Task<int> SaveAsync();}The Unit of Work will allow us later to inject it as a service for any repository. If you inspect the interface closely, you will notice it has three fields. The most vital of the three is the Repository. The method returns a domain of type repository and key. You can specify the type when using it.
Moving on to the Code First portion, we must tell Entity Framework how to build our database. To do so, we can create a “BloggingContext”.
public class BloggingContext: DbContext{ // Use design time factory public BloggingContext(DbContextOptions<BloggingContext> dbContextOptions) : base(dbContextOptions) { } public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; }}If you inspect the code closely, you will notice that we inherited from DbContext, which allows us to manipulate the database. The DbContext will also enable us to use DbSets and CRUD methods. You can read more about DbContext Class on the Microsoft website.
Before using your Database Context with Code, you must set up migrations. Migrations allow you to evolve your database as you code and change the schema. I recommend you read up on Migrations managing schemas because it has excellent examples to help you start quickly.
At the high level, in Visual Studio, open up the Tools menu, then the NuGet Package Manager menu, followed by the Console. In the Console, you must install the following package.
Install-Package Microsoft.EntityFrameworkCore.Tools
The Microsoft.EntityFrameworkCore.Tools will allow you to make the following commands.
Add-Migration InitialCreate
Update-Database
Meanwhile, you might want to consider making a DesignTimeDbContextFactory because it aids in setting up the connection string for the database.
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<BloggingContext>{ public BloggingContext CreateDbContext(string[] args) { // Build configuration IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.Development.json") .Build(); // Get connection string var connectionString = configuration.GetConnectionString("DefaultConnection"); var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>(); optionsBuilder.UseSqlServer(connectionString); return new BloggingContext(optionsBuilder.Options); }}I’m considering publishing the fully working example on Git with the following components.
- Services
- Domain
- Interfaces
- Repository
- Console App with basic CRUD operations
- Dependency Injection
Current Donation Amount
$2.41 – PayPal fees 🤑
Note that the donation amount is being updated manually on my end. I have asked WordPress; see the image for details. I will list your name and last name initials. If you like the website backlink, donate $10 or more, and let me know in the comments your web address.
Donate to Goal of $666 to unlock Code First Generic Repository Pattern 🚀✨
Upon reaching the $666 Goal, I will share the code.
$3.00
Donators List
- Nicholas S 8.20.2024
#CodeEfficiency #CodeFirst #CRUDOperations #CSharp #DatabaseManagement #DbContext #DependencyInjection #DesignPatterns #EntityFramework #GenericRepository #Migrations #RepositoryPattern #SoftwareDevelopment #UnitofWork
-
Have you ever dreaded writing the same boilerplate repository code repeatedly? You’re not alone; I will share my implementation of the Code First Generic Repository Pattern in C#. I will only include some of the code because it will make the post incredibly long. At the end of the post, I will share a Goal donation to post a Git download link so you can take it for a spin. As a bonus, the repository uses Code First and Unit of Work.
Generic Repository Pattern in C#
Let’s begin with the Entity interface. The IEntity interface is a typical pattern used in software development to define a contract for entities, typically in the context of data access and persistence. It usually includes a property for the entity’s unique identifier. The Generic Type: The IEntity interface uses a generic type parameter TKey to allow flexibility in the type of the identifier (e.g., int, Guid, string). The ID property will identify each entity uniquely. Feel free to read more about the implementation at the entity framework core generic repository and Structured Query IEntity.
public interface IEntity<TKey>{ TKey Id { get; set; }}You might find the following definition of the generic repository pattern on the interwebs.
The Generic Repository pattern in C# is a design pattern that abstracts the application’s data layer, making it easier to manage data access logic across different data sources. It aims to reduce redundancy by implementing typical data operations in a single, generic repository rather than having separate repositories for each entity type.
public interface IGenericRepository<TEntity, TKey> where TEntity : class, IEntity<TKey>{ void Delete(TEntity entityToDelete); TEntity? GetFirstOrDefault(Expression<Func<TEntity, bool>> predicate); void Update(TEntity entityToUpdate); void Save(); void Dispose();}The interface header has two generic types. TEntity is the domain class, and the TKey is the ID type, int, or string. Note that IEntity abstracts away the type TKey. It looks complex for the moment, but you will see benefits later.
Moving away from the Generic Repository, let’s focus on the pattern of the Unit of Work. According to Copilot:
The Unit of Work is a design pattern used in software development to manage and coordinate changes to a database. It ensures that all operations within a single business transaction are treated as a single unit, which means they either all succeed, or all fail together. This helps maintain data integrity and consistency.
public interface IUnitOfWork : IDisposable{ IGenericRepository<TEntity, TKey> Repository<TEntity, TKey>() where TEntity : class, IEntity<TKey>; void Save(); Task<int> SaveAsync();}The Unit of Work will allow us later to inject it as a service for any repository. If you inspect the interface closely, you will notice it has three fields. The most vital of the three is the Repository. The method returns a domain of type repository and key. You can specify the type when using it.
Moving on to the Code First portion, we must tell Entity Framework how to build our database. To do so, we can create a “BloggingContext”.
public class BloggingContext: DbContext{ // Use design time factory public BloggingContext(DbContextOptions<BloggingContext> dbContextOptions) : base(dbContextOptions) { } public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; }}If you inspect the code closely, you will notice that we inherited from DbContext, which allows us to manipulate the database. The DbContext will also enable us to use DbSets and CRUD methods. You can read more about DbContext Class on the Microsoft website.
Before using your Database Context with Code, you must set up migrations. Migrations allow you to evolve your database as you code and change the schema. I recommend you read up on Migrations managing schemas because it has excellent examples to help you start quickly.
At the high level, in Visual Studio, open up the Tools menu, then the NuGet Package Manager menu, followed by the Console. In the Console, you must install the following package.
Install-Package Microsoft.EntityFrameworkCore.Tools
The Microsoft.EntityFrameworkCore.Tools will allow you to make the following commands.
Add-Migration InitialCreate
Update-Database
Meanwhile, you might want to consider making a DesignTimeDbContextFactory because it aids in setting up the connection string for the database.
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<BloggingContext>{ public BloggingContext CreateDbContext(string[] args) { // Build configuration IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.Development.json") .Build(); // Get connection string var connectionString = configuration.GetConnectionString("DefaultConnection"); var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>(); optionsBuilder.UseSqlServer(connectionString); return new BloggingContext(optionsBuilder.Options); }}I’m considering publishing the fully working example on Git with the following components.
- Services
- Domain
- Interfaces
- Repository
- Console App with basic CRUD operations
- Dependency Injection
Current Donation Amount
$2.41 – PayPal fees 🤑
Note that the donation amount is being updated manually on my end. I have asked WordPress; see the image for details. I will list your name and last name initials. If you like the website backlink, donate $10 or more, and let me know in the comments your web address.
Donate to Goal of $666 to unlock Code First Generic Repository Pattern 🚀✨
Upon reaching the $666 Goal, I will share the code.
$3.00
Donators List
- Nicholas S 8.20.2024
https://vyechi.com/2024/08/20/generic-repository-pattern-in-c/
#CodeEfficiency #CodeFirst #CRUDOperations #CSharp #DatabaseManagement #DbContext #DependencyInjection #DesignPatterns #EntityFramework #GenericRepository #Migrations #RepositoryPattern #SoftwareDevelopment #UnitofWork