<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Design Pattern - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/category/design-pattern/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Sat, 09 Mar 2024 22:09:02 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://thecodebuzz.com/wp-content/uploads/2022/11/cropped-android-chrome-512x512-1-1-51x51.jpg</url>
	<title>Design Pattern - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>What is Data Modelling &#8211; Fundamentals and Guidelines</title>
		<link>https://thecodebuzz.com/what-is-data-modelling-fundamentals-sql-nosql-guidelines/</link>
					<comments>https://thecodebuzz.com/what-is-data-modelling-fundamentals-sql-nosql-guidelines/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 25 Nov 2023 22:59:31 +0000</pubDate>
				<category><![CDATA[Database Best Practices]]></category>
		<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Data Modelling - Fundamentals and Guidelines]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=28855</guid>

					<description><![CDATA[<p>What is Data Modelling &#8211; Fundamentals and Guidelines Today in this article, we will go over Data Modelling &#8211; Fundamentals and Building Blocks and their usage guidelines. What is Data Modelling Data modeling is an important technique for effective database design, understanding the data requirements of a particular use case, and offering a structured method [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/what-is-data-modelling-fundamentals-sql-nosql-guidelines/">What is Data Modelling – Fundamentals and Guidelines</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">What is Data Modelling &#8211; Fundamentals and Guidelines</h1>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="666" height="324" src="https://www.thecodebuzz.com/wp-content/uploads/2023/11/what-is-data-modelling-fundamentals-sql-nosql-guidelines.jpg" alt="What is Data Modelling - Fundamentals and Guidelines" class="wp-image-29209" srcset="https://thecodebuzz.com/wp-content/uploads/2023/11/what-is-data-modelling-fundamentals-sql-nosql-guidelines.jpg 666w, https://thecodebuzz.com/wp-content/uploads/2023/11/what-is-data-modelling-fundamentals-sql-nosql-guidelines-300x146.jpg 300w" sizes="(max-width: 666px) 100vw, 666px" /></figure>



<p>Today in this article, we will go over Data Modelling &#8211; Fundamentals and Building Blocks and their usage guidelines.</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-what-is-data-modelling">What is Data Modelling</a></li><li><a href="#aioseo-sql-and-no-sql-data-modelling-is-still-valid-techniques">SQL and NO SQL &#8211; Data modeling is still a valid technique</a></li><li><a href="#aioseo-type-of-data-dodeling-concepts">Type of Data Modeling Concepts</a><ul><li><a href="#aioseo-conceptual-data-modeling">Conceptual Data Modeling</a></li><li><a href="#aioseo-logical-data-modeling">Logical Data Modeling</a></li><li><a href="#aioseo-physical-data-modeling">Physical Data Modeling:</a></li></ul></li><li><a href="#aioseo-building-blocks-of-data-modeling">Building blocks of Data modeling</a><ul><li><a href="#aioseo-entities-in-data-modelling">Entities in Data Modelling</a></li><li><a href="#aioseo-attributes-in-data-modelling">Attributes in Data Modelling</a></li><li><a href="#aioseo-relationships-in-data-modeling">Relationships in Data modeling</a></li><li><a href="#aioseo-keys-in-data-modeling">Keys in Data modeling</a></li><li><a href="#aioseo-benefits-of-data-modeling">Benefits of Data Modeling</a></li><li><a href="#aioseo-data-modeling-tools">Data modeling Tools</a></li></ul></li></ul></div>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-what-is-data-modelling">What is Data Modelling </h2>



<p></p>



<p><a href="https://www.thecodebuzz.com/mongodb-schema-design-guidelines-best-practices/" target="_blank" rel="noopener" title="MongoDB Schema Design – Guidelines and Best practices">Data modeling</a> is an important technique for effective database design, understanding the data requirements of a particular use case, and offering a structured method for understanding, representing, and implementing data structures for a given requirement.</p>



<p></p>



<p>Data Modelling normally occurs at the beginning of the development process to understand and document business requirements before database implementation. </p>



<p></p>



<p>This means it heavily helps you identify and documentation of business logic, rules, and relationships to ensure that the data model aligns with business objectives.</p>



<p></p>



<p>Data modeling focuses on organizing data at a <strong>Conceptual </strong>or <strong>Abstract or </strong> <strong>Physical </strong>level. </p>



<p></p>



<p>It aims to understand the information requirements of a business or system and define the relationships between different data entities. </p>



<p></p>



<p>Data modeling utilizes techniques like Entity-Relationship Diagrams (<strong>ERD</strong>) to represent entities, attributes, and relationships between entities, but this evolution and brainstorming does help you define your requirements in a true sense. </p>



<p></p>



<p>Along with facilitating discussions, it ensures changes to the design are visited during the early stages of development. In the world of development, which fully relies on design in the first place this does help in a greater way.</p>



<p></p>



<p>Data Modelling encourages communication between various stakeholders including the product owner, scrum, developers, or architects by providing a visual representation of data concepts that is accessible to both technical and non-technical audiences.</p>



<p></p>



<p>It very good technique for extending logical and physical design, normalization, relationship mapping, and performance optimization at the very beginning of use case or requirements explorations.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-sql-and-no-sql-data-modelling-is-still-valid-techniques">SQL and NO SQL &#8211; Data modeling is still a valid technique</h2>



<p></p>



<p>Data Modelling operates at a more elevated level of <strong>abstraction</strong>, stressing entities, attributes, and relationships without getting into specific database implementation details, and hence this technique&#8217;s value holds for SQL or No SQL database design.</p>



<p> </p>



<p>The outcomes of Data modeling ensure conceptualization, understanding, and representation of data requirements to various stake stakeholders and hence build confidence in the product which is going to evolve later stage as deliverables.</p>



<p></p>



<p></p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="278" src="https://www.thecodebuzz.com/wp-content/uploads/2023/11/Data-Modelling-vs-schema-modelling-1024x278.jpg" alt="" class="wp-image-28859" srcset="https://thecodebuzz.com/wp-content/uploads/2023/11/Data-Modelling-vs-schema-modelling-1024x278.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/11/Data-Modelling-vs-schema-modelling-300x81.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/11/Data-Modelling-vs-schema-modelling-768x208.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/11/Data-Modelling-vs-schema-modelling-1536x417.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2023/11/Data-Modelling-vs-schema-modelling-785x213.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/11/Data-Modelling-vs-schema-modelling.jpg 1770w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<h2 class="wp-block-heading" id="aioseo-type-of-data-dodeling-concepts">Type of Data Modeling Concepts</h2>



<p></p>



<h3 class="wp-block-heading" id="aioseo-conceptual-data-modeling"><strong>Conceptual Data Modeling</strong></h3>



<p></p>



<ul class="wp-block-list">
<li>Focuses on the high-level representation of the domain entities, business concepts, and relationships within a system.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li>Helps in getting all the the fundamental entities, attributes, and relationships between.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li>Provide a clear and abstract view of the business requirements, serving as a foundation for further development.</li>
</ul>



<p></p>



<h3 class="wp-block-heading" id="aioseo-logical-data-modeling"><strong>Logical Data Modeling</strong></h3>



<p></p>



<ul class="wp-block-list">
<li>This modeling helps translate the conceptual data model into a more detailed and structured format that can be implemented in a database.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li>Defines tables, columns, fields, data types, relationships, and constraints for the given database management system.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li>It acts as a bridge between the conceptual model and the physical implementation, ensuring a comprehensive and consistent representation of data.</li>
</ul>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-physical-data-modeling"><strong>Physical Data Modeling:</strong></h3>



<p></p>



<p></p>



<ul class="wp-block-list">
<li>Focuses on the actual implementation of the database on a specific database management system SQL or  No SQL.</li>
</ul>



<p></p>



<p></p>



<ul class="wp-block-list">
<li>Includes details such as storage structures, indexing, partitioning, and other optimization techniques to enhance performance.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li>Involves decisions about how data is stored, accessed, and retrieved at the physical level, considering the specific features and requirements of the chosen DBMS.</li>
</ul>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-building-blocks-of-data-modeling"><strong>Building blocks of Data modeling </strong></h2>



<p></p>



<h3 class="wp-block-heading" id="aioseo-entities-in-data-modelling">Entities in Data Modelling </h3>



<p></p>



<figure class="wp-block-image size-full is-resized"><img decoding="async" width="684" height="540" src="https://www.thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Fundamentals.jpg" alt="" class="wp-image-28860" style="aspect-ratio:1.2666666666666666;width:683px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Fundamentals.jpg 684w, https://thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Fundamentals-300x237.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Fundamentals-659x520.jpg 659w" sizes="(max-width: 684px) 100vw, 684px" /></figure>



<p></p>



<p>The best way to judge an entity is as some type of &#8220;<strong><em>real-world subject</em></strong>.&#8221;</p>



<p></p>



<p>At the end entity represents &#8221; <strong><em>a collection of attributes or fields</em></strong>.&#8221;</p>



<p></p>



<p>Entities represent distinct objects, concepts, or things within a system that are described and stored as data. </p>



<p></p>



<p>These entities encapsulate relevant information through attributes, defining the properties or characteristics associated with them. </p>



<p></p>



<p>For example, in a customer relationship system, a &#8220;Customer&#8221; entity might include attributes such as &#8220;CustomerID,&#8221; &#8220;Name,&#8221; and &#8220;Email.&#8221; </p>



<p></p>



<p>Identifying and modeling entities is foundational for a clear understanding of the information requirements and relationships within a given domain or system.</p>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-attributes-in-data-modelling">Attributes in Data Modelling </h3>



<p></p>



<p>Attributes provide granularity to the data model, offering a way to distinguish and categorize information within entities.</p>



<p></p>



<figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" width="862" height="434" src="https://www.thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Entity-Data-Model-and-attribute-examples.jpg" alt="Data Modelling Fundamentals and Building Blocks" class="wp-image-28865" style="aspect-ratio:1.9861751152073732;width:840px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Entity-Data-Model-and-attribute-examples.jpg 862w, https://thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Entity-Data-Model-and-attribute-examples-300x151.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Entity-Data-Model-and-attribute-examples-768x387.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Entity-Data-Model-and-attribute-examples-785x395.jpg 785w" sizes="auto, (max-width: 862px) 100vw, 862px" /></figure>



<p>By defining these attributes, data modeling achieves a more comprehensive representation of the underlying data, enabling the organization and retrieval of specific details associated with each entity in a structured and meaningful manner.</p>



<p></p>



<p>Characteristics or properties of <a href="https://www.thecodebuzz.com/getting-started-efcore-entity-framework-core-orm-asp-net-core/" target="_blank" rel="noopener" title="Getting Started with Entity Framework – ORM in ASP.NET Core">entities </a>that describe the data associated with them. </p>



<p></p>



<p>Attributes provide details about the entities and are often represented as adjectives, like &#8220;<strong>Name</strong>&#8221; or &#8220;<strong>DateOfBirth</strong>.&#8221;</p>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-relationships-in-data-modeling">Relationships in Data modeling</h3>



<p></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="706" height="607" src="https://www.thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Fundamentals-attributes-and-relationship.jpg" alt="" class="wp-image-28864" srcset="https://thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Fundamentals-attributes-and-relationship.jpg 706w, https://thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Fundamentals-attributes-and-relationship-300x258.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Fundamentals-attributes-and-relationship-605x520.jpg 605w" sizes="auto, (max-width: 706px) 100vw, 706px" /></figure>



<p>In data modeling, relationships establish <a href="https://www.thecodebuzz.com/database-connection-resiliency-entity-framework-asp-net-core/">connections between entities,</a> defining how they interact. T</p>



<p></p>



<p>These connections convey associations and dependencies, crucial for understanding the dynamics within a system. </p>



<p></p>



<p>For instance, in a database for a library, a &#8220;Customer&#8221; entity may have a relationship with an &#8220;Order&#8221; entity, indicating the association between individuals requesting an order. </p>



<p></p>



<ul class="wp-block-list">
<li>Relationships specify the cardinality and nature of connections, such as one-to-one or many-to-many, providing a structured framework for data representation. </li>
</ul>



<p></p>



<ul class="wp-block-list">
<li>By modeling relationships, data modeling ensures a comprehensive understanding of how entities relate to one another, fostering accurate and efficient retrieval of information from the database.</li>
</ul>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-keys-in-data-modeling">Keys in Data modeling</h3>



<p></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="722" height="659" src="https://www.thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Fundamentals-relationship-and-keys-defined.jpg" alt="" class="wp-image-28868" srcset="https://thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Fundamentals-relationship-and-keys-defined.jpg 722w, https://thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Fundamentals-relationship-and-keys-defined-300x274.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/11/Mastering-Data-Modeling-Fundamentals-relationship-and-keys-defined-570x520.jpg 570w" sizes="auto, (max-width: 722px) 100vw, 722px" /></figure>



<ul class="wp-block-list">
<li>Keys play a pivotal role in data modeling by uniquely identifying and organizing data within a database.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li><strong>In RDBMS or SQL </strong>worlds example &#8211; the &#8220;primary key&#8221; serves as a distinct identifier for each record, ensuring data integrity.
<ul class="wp-block-list">
<li>Foreign keys establish relationships between tables, linking data across entities. </li>



<li>Index keys enhance query performance, enabling swift data retrieval.</li>



<li>Composite keys combine multiple attributes to create a unique identifier.</li>
</ul>
</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li>In <strong>No SQL</strong> Unique Keys identify documents or entries within a collection, ensuring data integrity.
<ul class="wp-block-list">
<li>In document-oriented databases, like MongoDB, keys often include a unique identifier, such as the document&#8217;s &#8220;_id.&#8221;</li>



<li>In key-value stores, like Redis, keys serve as direct access points to values.</li>



<li>NoSQL databases may also use composite keys or secondary indexes for diverse query patterns.</li>



<li>Keys are crucial for optimizing data access, retrieval, and navigation in NoSQL databases, contributing to performance in managing various data structures and relationships.</li>
</ul>
</li>
</ul>



<p></p>



<h3 class="wp-block-heading" id="aioseo-benefits-of-data-modeling">Benefits of Data Modeling</h3>



<p></p>



<p>Below are the top-level benefits of data modeling.</p>



<p></p>



<ul class="wp-block-list">
<li>Creating a structure for collaboration between your IT and business teams.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li>Revealing opportunities for improving business processes by defining data needs and uses.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li>Saving time and money on IT and process investments through appropriate planning.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li>Reducing errors (and error-prone redundant data entry) while improving data integrity.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li>Increasing the speed and performance of data retrieval and analytics by planning for capacity and growth.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li>Setting and tracking target key performance indicators tailored to your business objectives.</li>
</ul>



<p></p>



<h3 class="wp-block-heading" id="aioseo-data-modeling-tools"><strong>Data modeling Tools</strong></h3>



<p></p>



<p>Here are a few useful tools for Data modeling examples:</p>



<p></p>



<ul class="wp-block-list">
<li><strong>erwin Data Modeler</strong> is a data modeling tool based on the Integration DEFinition for information modeling (IDEF1X) data modeling language that now supports other notation methodologies, including a dimensional approach.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li><strong>Enterprise Architect</strong> is a visual modeling and design tool that supports the modeling of enterprise information systems and architectures. It’s based on object-oriented languages and standards.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li><strong>ER/Studio</strong> is database design software that’s compatible with several of today’s most popular database management systems. It supports both relational and dimensional data modeling.</li>
</ul>



<p></p>



<ul class="wp-block-list">
<li><strong>Open Source tools</strong> include open-source solutions such as Open ModelSphere.</li>
</ul>



<p></p>



<p></p>



<p>That&#8217;s all! Happy coding!</p>



<p></p>



<p>Does this help you fix your issue? </p>



<p></p>



<p>Do you have any better solutions or suggestions? Please sound off your comments below.</p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/what-is-data-modelling-fundamentals-sql-nosql-guidelines/">What is Data Modelling – Fundamentals and Guidelines</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/what-is-data-modelling-fundamentals-sql-nosql-guidelines/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Entity Framework Repository Implementation in ASP.NET Core</title>
		<link>https://thecodebuzz.com/entity-framework-repository-implementation-efcore-net-core/</link>
					<comments>https://thecodebuzz.com/entity-framework-repository-implementation-efcore-net-core/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 22 Mar 2023 23:47:00 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[EFCore]]></category>
		<category><![CDATA[efcore net core repository]]></category>
		<category><![CDATA[efcore repository]]></category>
		<category><![CDATA[Entity Framework Repository Implementation in ASP.NET Core]]></category>
		<category><![CDATA[entity framework repository pattern]]></category>
		<category><![CDATA[generic repository pattern c# with dependency injection net core]]></category>
		<category><![CDATA[generic repository pattern in asp.net core]]></category>
		<category><![CDATA[generic repository pattern in asp.net core web api]]></category>
		<category><![CDATA[repository pattern and unit of work with entity framework in asp.net core]]></category>
		<category><![CDATA[repository pattern in asp.net core example]]></category>
		<category><![CDATA[repository pattern in asp.net core mvc]]></category>
		<category><![CDATA[should i use repository pattern with entity framework core]]></category>
		<category><![CDATA[using dbcontext in repositry]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=8572</guid>

					<description><![CDATA[<p>EFCore Repository Implementation in ASP.NET Core In this article, we will learn Entity Framework Repository Implementation for Relational databases like SQL in the .NET Core or ASP.NET Core 3.1 or .NET 6 application. We already discussed basic details on getting started with EFCore in ASP.NET Core in our last article. In Today&#8217;s article, we shall [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/entity-framework-repository-implementation-efcore-net-core/">Entity Framework Repository Implementation in ASP.NET Core</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">EFCore Repository Implementation in ASP.NET Core </h1>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="513" src="https://www.thecodebuzz.com/wp-content/uploads/2020/03/EFCore-Repository-Implementation-in-.NET-Core-with-Unit-Testing-example-1024x513.jpg" alt="Entity Framework Repository Implementation in ASP.NET Core" class="wp-image-8576" srcset="https://thecodebuzz.com/wp-content/uploads/2020/03/EFCore-Repository-Implementation-in-.NET-Core-with-Unit-Testing-example-1024x513.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/03/EFCore-Repository-Implementation-in-.NET-Core-with-Unit-Testing-example-300x150.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/03/EFCore-Repository-Implementation-in-.NET-Core-with-Unit-Testing-example-768x385.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/03/EFCore-Repository-Implementation-in-.NET-Core-with-Unit-Testing-example-785x393.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/03/EFCore-Repository-Implementation-in-.NET-Core-with-Unit-Testing-example.jpg 1223w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>In this article, we will learn<strong><em> Entity Framework Repository </em></strong>Implementation for Relational databases like SQL in the .NET Core or ASP.NET Core 3.1 or .NET 6 application.</p>



<p></p>



<p>We already discussed basic details on getting started with <a href="https://www.thecodebuzz.com/getting-started-efcore-entity-framework-core-orm-asp-net-core/" target="_blank" rel="noreferrer noopener">EFCore in ASP.NET Core </a>in our last article.</p>



<p></p>



<p>In Today&#8217;s article, we shall see how to extend the same existing implementation to use a better pattern i.e Repository.</p>



<p></p>



<p></p>



<p>Below are the steps which we shall be following to create a Repository,</p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#EFCore-scaffolding">EFCore scaffolding as Repository and UoW</a></li><li><a href="#aioseo-entity-framework-dbcontext-as-repository-and-uow">Entity Framework DBContext as Repository and UOW</a></li><li><a href="#schema">Entity Framework- Create Models using Schema</a></li><li><a href="#aioseo-entity-framework-using-database-first">Entity Framework  &#8211; using Database First</a></li><li><a href="#define-repository-interface">Entity Framework- Define Repository Interfaces</a></li><li><a href="#define-repository-class">Entity Framework- Define Repository Class</a></li><li><a href="#aioseo-using-a-repository-in-api-service">Using a Repository in API/Service</a></li><li><a href="#use-repository-ioc">Repository and DBContext using IoC Dependency injection Container</a><ul><li><a href="#aioseo-dependency-injection-container-in-net-3-1-or-5">Dependency injection Container in .NET 3.1</a></li><li><a href="#aioseo-dependency-injection-container-in-net-3-1-or-5">Dependency injection Container in .NET 6 and above</a></li></ul></li><li><a href="#conclusion">Summary</a></li></ul></div>



<p></p>



<h2 class="wp-block-heading" id="EFCore-scaffolding">EFCore scaffolding as Repository and UoW</h2>



<p></p>



<p><strong>EFCore&nbsp;</strong>is an&nbsp;<strong>ORM-Object-relational mapping</strong>&nbsp;framework that helps to represent the Database into the object-oriented programming model in the .NET Core ecosystem helping to interact and perform <strong>CRUD </strong>operation on relational DB without hassle. </p>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>Repository design patterns fit into any NoSQL or Relational DB requirements and also can be used for multiple other requirements.</p>
</blockquote>



<p></p>



<h2 class="wp-block-heading" id="aioseo-entity-framework-dbcontext-as-repository-and-uow"><strong>Entity Framework DBContext as Repository and UOW</strong></h2>



<p></p>



<p>Using tools like <strong>Entity Framework </strong>gives us <strong>DBContext </strong>which already represents repository and UoW (Unit Of Work) implementation with very minimal effort. </p>



<p></p>



<p>The best thing is you can use <strong>DBContext </strong>anywhere from your code.</p>



<p></p>



<p>This DBContext can be DI (Dependency Injected ) from the API pipeline or Middleware as needed or can be consumed directly.</p>



<p></p>



<p>However, if you see <strong>DBContext </strong>is a class and not an Interface. </p>



<p></p>



<p>If you need to perform <strong>Test-Driven Development</strong> like Unit Testing, you will find a few challenges in <a href="https://www.thecodebuzz.com/unit-test-mock-entity-framework-core-repository/" target="_blank" rel="noreferrer noopener">mocking DBContext</a> to simulate the Data access. </p>



<p></p>



<p>So considering testability as an important principle, one can easily implement a Repository. </p>



<p></p>



<p>Repository encourages a more loosely coupled approach to accessing our data from the database. </p>



<p></p>



<p>The code becomes cleaner and maintainable and highly extensible.</p>



<p></p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" width="1756" height="796" src="https://i2.wp.com/thecodebuzz.com/wp-content/uploads/2019/11/image-4.png?fit=785%2C356&amp;ssl=1" alt="Entity Framework Repository Implementation in ASP.NET Core" class="wp-image-6292" srcset="https://thecodebuzz.com/wp-content/uploads/2019/11/image-4.png 1756w, https://thecodebuzz.com/wp-content/uploads/2019/11/image-4-300x136.png 300w, https://thecodebuzz.com/wp-content/uploads/2019/11/image-4-1024x464.png 1024w, https://thecodebuzz.com/wp-content/uploads/2019/11/image-4-768x348.png 768w, https://thecodebuzz.com/wp-content/uploads/2019/11/image-4-1536x696.png 1536w, https://thecodebuzz.com/wp-content/uploads/2019/11/image-4-785x356.png 785w" sizes="auto, (max-width: 1756px) 100vw, 1756px" /></figure>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="schema">Entity Framework- Create Models using Schema</h2>



<p></p>



<p>Do you follow <strong><em>schema modeling</em></strong> ??.</p>



<p></p>



<p>EFCore works very well for the <strong>Database First </strong>approach. </p>



<p>Where it lets you create the required <em><a href="https://www.thecodebuzz.com/efcore-scaffold-dbcontext-commands-orm-net-core/" title="Understanding EFCore scaffold-dbcontext Commands in .NET Core">scaffolding </a></em>and domain entities using the existing Database.</p>



<p></p>



<p>However, You can follow the <strong>code-first </strong>approach as well followed by using Migration and Update database commands to create the database.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-entity-framework-using-database-first">Entity Framework  &#8211; using Database First</h2>



<p></p>



<p>We shall be learning <a href="https://www.thecodebuzz.com/getting-started-efcore-entity-framework-core-orm-asp-net-core/" target="_blank" rel="noreferrer noopener"><em><strong>EFCore using Database first</strong></em></a> approach where we already have an existing&nbsp;<strong>Database&nbsp;</strong>called ‘<strong>Master</strong>‘ and a&nbsp;<strong>table&nbsp;</strong>name called&nbsp;<strong>Employee</strong>.</p>



<p></p>



<p><strong>SQL Database Schema</strong></p>



<p></p>



<p>We can start with the below simple Database schema,</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="345" src="https://www.thecodebuzz.com/wp-content/uploads/2020/03/EFCore-in-ASP.NET-Core-1024x345.jpg" alt="EFCore Database First, Entity Framework Database First" class="wp-image-8573" srcset="https://thecodebuzz.com/wp-content/uploads/2020/03/EFCore-in-ASP.NET-Core-1024x345.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/03/EFCore-in-ASP.NET-Core-300x101.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/03/EFCore-in-ASP.NET-Core-768x259.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/03/EFCore-in-ASP.NET-Core-1536x517.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/03/EFCore-in-ASP.NET-Core-785x264.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/03/EFCore-in-ASP.NET-Core.jpg 1820w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p>I have discussed how to do ECore scaffolding and generate domain entities in the below article.</p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/efcore-scaffold-dbcontext-commands-orm-net-core/" target="_blank" rel="noreferrer noopener"><strong><em>Scaffold &#8211; DBContext Database command in .NET Core</em></strong></a></li>
</ul>



<p></p>



<p>Once you are ready with scaffolding please use the repository to access <strong>DBContext </strong>objects as below.</p>



<p></p>



<h2 class="wp-block-heading" id="define-repository-interface">Entity Framework- Define Repository Interfaces</h2>



<p></p>



<p>Repository Interfaces will be defined as below,</p>



<p></p>



<pre class="wp-block-code"><code>public interface IEmployeeRepository
{
    IEnumerable&lt;Employee&gt; GetEmployees();
    Employee GetEmployeeByID(int employeeID);
    void InsertEmployee(Employee employee);
    void DeleteEmployee(int employeeID);
    void UpdateEmployee(Employee employee);
}</code></pre>



<p></p>



<p>We shall define repository class specific to the context, i.e. here <strong>EmployeeRepository </strong>will be dealing with Employee <strong>DBContext</strong>. </p>



<p></p>



<h2 class="wp-block-heading" id="define-repository-class">Entity Framework- Define Repository Class</h2>



<p></p>



<p>Please see the implementation for the Repository class performing CRUD operation below.</p>



<p></p>



<p><strong>EmployeeContext </strong>object is accessed using  EmployeeRepository Constructor injections as below,</p>



<p></p>



<pre class="wp-block-code"><code>public class EmployeeRepository : IEmployeeRepository
    {
        private readonly EmployeeContext _context;
        public EmployeeRepository(EmployeeContext context)
        {
            _context = context;
        }
        public IEnumerable&lt;Employee&gt; GetEmployees()
        {
            return _context.Employee.ToList();
        }
        public Employee GetEmployeeByID(int employeeID)
        {
            return _context.Employee.Find(employeeID.ToString());
        }
        public void InsertEmployee(Employee employee)
        {
            _context.Employee.Add(employee);
        }
        public void DeleteEmployee(int employeeID)
        {
            Employee employee = _context.Employee.Find(employeeID);
            _context.Employee.Remove(employee);
        }
        public void UpdateEmployee(Employee employee)
        {
            _context.Entry(employee).State = EntityState.Modified;
        }
    }</code></pre>



<p></p>



<p><strong>EmployeeContext </strong>is created using database <a href="https://www.thecodebuzz.com/efcore-scaffold-dbcontext-commands-orm-net-core/" target="_blank" rel="noreferrer noopener">Scaffolding DBContext Commands </a>as discussed in our <a href="https://www.thecodebuzz.com/efcore-scaffold-dbcontext-commands-orm-net-core/" target="_blank" rel="noreferrer noopener">Getting Started using EFCore</a> article. </p>



<p></p>



<p>Now that our Repository is ready, this can be integrated into the code.</p>



<p></p>



<p>If following non-DDD or DDD architecture this repository will be responsible for performing CRUD and will also be used for data persistence through DBContext.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-using-a-repository-in-api-service">Using a Repository in API/Service</h2>



<p></p>



<p>Here is an example of how I am using the repository in&nbsp;<strong>EmployeeController </strong>(In a similar way this repository can be interfaced from&nbsp;the <strong>Domain&nbsp;</strong>or&nbsp;<strong>Business&nbsp;</strong>layer as required (if you have any).</p>



<p></p>



<p>EmployeeRepository object is accessed using EmployeeController&#8217;s Constructor injections.</p>



<p></p>



<p>Below is a very simple and minimal implementation,</p>



<p></p>



<pre class="wp-block-code"><code>    &#91;Route("api/&#91;controller]")]
    &#91;ApiController]
    public class EmployeeController : ControllerBase
    {
        private readonly IEmployeeRepository _employeeRepository;
        public EmployeeController(IEmployeeRepository employeeRepository)
        {
            _employeeRepository = employeeRepository;
        }
        // GET: api/Employee
        &#91;HttpGet]
        public ActionResult&lt;IEnumerable&lt;Employee>> Get()
        {
            return Ok(_employeeRepository.GetEmployees());
        }
        // GET: api/Employee/5
        &#91;HttpGet("{id}")]
        public ActionResult Get(int id)
        {
            return Ok(_employeeRepository.GetEmployeeByID(id));
        }
        // POST: api/Employee
        &#91;HttpPost]
        public void Post(&#91;FromBody] Employee value)
        {
            _employeeRepository.InsertEmployee(value);
        }
        // DELETE: api/5
        &#91;HttpDelete("{id}")]
        public void Delete(int employeeID)
        {
            _employeeRepository.DeleteEmployee(employeeID);
        }
    }</code></pre>



<p></p>



<h2 class="wp-block-heading" id="use-repository-ioc">Repository and DBContext using IoC Dependency injection Container</h2>



<p></p>



<p>Please initialize Repository and <strong>DBContext </strong>in the Service Container as below,</p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-dependency-injection-container-in-net-3-1-or-5">Dependency injection Container in .NET 3.1 </h3>



<p></p>



<pre class="wp-block-code"><code>public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddScoped&lt;IEmployeeRepository, EmployeeRepository>();
            services.AddDbContext&lt;EmployeeContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("EmployeeDB"),
                 sqlServerOptionsAction: sqlOptions =>
                 {
                     sqlOptions.EnableRetryOnFailure();
                 });
            });
        }</code></pre>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"></blockquote>



<h3 class="wp-block-heading" id="aioseo-dependency-injection-container-in-net-3-1-or-5">Dependency injection Container in .NET 6 and above </h3>



<p></p>



<p>If using<strong> .NET 6 and above</strong>, please use builder instances to add the lifetime of required services,</p>



<p></p>



<p><strong>Example </strong></p>



<pre class="wp-block-code"><code>        
            builder.services.AddScoped&lt;IEmployeeRepository, EmployeeRepository>();
            builder.services.AddDbContext&lt;EmployeeContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("EmployeeDB"),
                 sqlServerOptionsAction: sqlOptions =>
                 {
                     sqlOptions.EnableRetryOnFailure();
                 });
            });</code></pre>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p></p>



<p>Please note that the repository instance lifetime in your IoC container should be set as <strong>Scoped </strong>(same as <strong><em>DBContext</em></strong>) as a good practice.</p>
</blockquote>



<p></p>



<p>As shown in the above code, we also have <a href="https://www.thecodebuzz.com/database-connection-resiliency-entity-framework-asp-net-core/" target="_blank" rel="noreferrer noopener"><em><strong>resiliency implemented for SQL Connection</strong></em></a> using <strong>EnableRetryOnFailure</strong>() added with the <strong><em>DBContext </em></strong>instance.</p>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>As a good practice, <a href="https://www.thecodebuzz.com/database-connection-resiliency-entity-framework-asp-net-core/" target="_blank" rel="noreferrer noopener"><strong><em>implement resiliency in SQL operation</em></strong></a> to address any issues related to Transient errors.</p>
</blockquote>



<p></p>



<p>One can also implement a more Generic repository around DBContext if needed addressing multiple Domain models as discussed below article if needed.</p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/mongodb-repository-implementation-unit-testing-net-core-example/" target="_blank" rel="noreferrer noopener"><em>MongoDB Generic Repository Implementation ASP.NET Core</em></a></li>
</ul>



<p></p>



<p>You are all set to use a repository in your code.</p>



<p></p>



<p><em>Other References :</em></p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/getting-started-efcore-entity-framework-core-orm-asp-net-core/" target="_blank" rel="noreferrer noopener"><em>Getting started with EFCore in .NET Core </em></a></li>
</ul>



<p></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="conclusion">Summary</h2>



<p></p>



<p>Today in this article we learned how to implement a <strong>Repository </strong>around SQL database using the <strong><em>EFCore ORM </em></strong>framework. </p>



<p></p>



<p>Application with a complex business/domain model gets a huge advantage over the <strong>Repository</strong>. </p>



<p>It provides an abstraction that not only isolates the business objects from the database access code but also provides a clean separation of concerns in an <strong><em>Object-oriented </em></strong>way.</p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p> </p><p>The post <a href="https://thecodebuzz.com/entity-framework-repository-implementation-efcore-net-core/">Entity Framework Repository Implementation in ASP.NET Core</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/entity-framework-repository-implementation-efcore-net-core/feed/</wfw:commentRss>
			<slash:comments>10</slash:comments>
		
		
			</item>
		<item>
		<title>Awesome Code &#8211; Middle Man Code Smell Resolution with examples</title>
		<link>https://thecodebuzz.com/middle-man-code-smell-resolution-examples/</link>
					<comments>https://thecodebuzz.com/middle-man-code-smell-resolution-examples/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 07 Dec 2022 04:01:00 +0000</pubDate>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[Awesome Code – Middle Man Code Smell Resolution with message chains code smell]]></category>
		<category><![CDATA[don't delete middle man that have been created for a]]></category>
		<category><![CDATA[examples]]></category>
		<category><![CDATA[inappropriate intimacy refactoring]]></category>
		<category><![CDATA[remove middle man]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=6216</guid>

					<description><![CDATA[<p>Middle Man Code Smell Resolution with examples Today in this article, we will talk about Middle Man Code Smell Resolution with examples. This code smell more talks about encapsulation. As we know there are many advantages of encapsulating the delegated objects and exposing the delegates directly. “Code is maintained more often than it is written” [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/middle-man-code-smell-resolution-examples/">Awesome Code – Middle Man Code Smell Resolution with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading"><strong>Middle Man Code Smell Resolution with examples</strong></h1>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" width="1307" height="504" src="https://i2.wp.com/thecodebuzz.com/wp-content/uploads/2019/10/Feature-envy-and-inappropriate-Intimacy-Code-smell-resoltion.jpg?fit=785%2C303&amp;ssl=1" alt="Middle Man Code Smell Resolution with examples" class="wp-image-6220" style="width:537px;height:206px" srcset="https://thecodebuzz.com/wp-content/uploads/2019/10/Feature-envy-and-inappropriate-Intimacy-Code-smell-resoltion.jpg 1307w, https://thecodebuzz.com/wp-content/uploads/2019/10/Feature-envy-and-inappropriate-Intimacy-Code-smell-resoltion-300x116.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/10/Feature-envy-and-inappropriate-Intimacy-Code-smell-resoltion-1024x395.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/10/Feature-envy-and-inappropriate-Intimacy-Code-smell-resoltion-768x296.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/10/Feature-envy-and-inappropriate-Intimacy-Code-smell-resoltion-785x303.jpg 785w" sizes="auto, (max-width: 1307px) 100vw, 1307px" /></figure>



<p>Today in this article, we will talk about Middle Man Code Smell Resolution with examples.</p>



<p></p>



<p>This code smell more talks about encapsulation. As we know there are many advantages of encapsulating the delegated objects and exposing the delegates directly.</p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-remove-middle-man">Remove Middle Man</a></li><li><a href="#aioseo-code-smell-examples">Code Smell examples</a></li><li><a href="#aioseo-resolution">Resolution</a></li></ul></div>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>“Code is maintained more often than it is written”</strong></p>
</blockquote>



<p>Middle Man code smells come under a category called ‘Couplers’. In our last article, we understood couplers with the smell of Inappropriate Intimacy. and Feature envy which talks about class relationships and features/functions/method coupling, etc.</p>



<p></p>



<p><strong>“Code is read more often than it is written”</strong></p>



<p></p>



<p>Today in this session we will talk about the encapsulation of delegates.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-remove-middle-man"><strong>Remove Middle Man</strong></h2>



<p></p>



<p>This is one of the code smell recipes to fix the code smell associated with delegated objects. </p>



<p>Let&#8217;s take an example with code smell,</p>



<h2 class="wp-block-heading" id="aioseo-code-smell-examples">Code Smell examples</h2>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
   class Program
    {
       static void Main(string&#x5B;] args)
        {
            Person person = new Person();
            person = person.GetManager();
        }
    }


    class Person
    {
        public Department Department { get; set; }
        public Person GetManager()
        {
            return Department.GetManager();
        }
    }


    class Department
    {
        private readonly Person _manager;
        public Department(Person manager)
        {
            _manager = manager;
        }
        public Person GetManager()
        {
            return _manager;
        }
    }
</pre></div>


<p></p>



<p>As in the above example, the Client class calls the Person&#8217;s delegated object to call the Department and get the manager&#8217;s details.</p>



<p></p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="1429" height="518" src="https://i0.wp.com/thecodebuzz.com/wp-content/uploads/2019/10/image-24.png?fit=785%2C284&amp;ssl=1" alt="Awesome Code - Middle Man Code Smell Resolution with examples" class="wp-image-6222" srcset="https://thecodebuzz.com/wp-content/uploads/2019/10/image-24.png 1429w, https://thecodebuzz.com/wp-content/uploads/2019/10/image-24-300x109.png 300w, https://thecodebuzz.com/wp-content/uploads/2019/10/image-24-1024x371.png 1024w, https://thecodebuzz.com/wp-content/uploads/2019/10/image-24-768x278.png 768w, https://thecodebuzz.com/wp-content/uploads/2019/10/image-24-785x285.png 785w" sizes="auto, (max-width: 1429px) 100vw, 1429px" /></figure>



<p></p>



<p>The issue with this approach is that every time the client wants to use the new feature of the delegates, the same feature needs to be added to the Person and Department as well.</p>



<p></p>



<p>To remediate this issue one can use a recipe called &#8220;Remove Middle Man&#8221;.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-resolution"><strong>Resolution</strong></h2>



<p></p>



<p>Let&#8217;s remove the Middle man and expose the delegates from both Person and department to the client directly. So the client talks and knows the object it calling.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
class Program
    {
        static void Main(string&#x5B;] args)
        {
            Person person = new Person();
            Department department = person.GetDepartment();
            person = department.GetManager();
        }
    }
    class Person
    {
        public Department Department;
        public Department GetDepartment()
        {
            return Department;
        }
 
    }

    class Department
    {
        private readonly Person _manager;
        public Department(Person manager)
        {
            _manager = manager;
        }
        public Person GetManager()
        {
            return _manager;
        }

    }
</pre></div>


<p></p>



<p>The client<strong> talks</strong> to the <em><strong>Person</strong></em> and the <em><strong>Department </strong></em>objects directly. This removes the middleman or encapsulation. Also now the client talks and knows who is he interacting with.</p>



<figure class="wp-block-image is-resized"><img loading="lazy" decoding="async" width="1046" height="924" src="https://i2.wp.com/thecodebuzz.com/wp-content/uploads/2019/10/image-25.png?fit=785%2C693&amp;ssl=1" alt="Awesome Code - Middle Man Code Smell Resolution with examples" class="wp-image-6223" style="width:539px;height:476px" srcset="https://thecodebuzz.com/wp-content/uploads/2019/10/image-25.png 1046w, https://thecodebuzz.com/wp-content/uploads/2019/10/image-25-300x265.png 300w, https://thecodebuzz.com/wp-content/uploads/2019/10/image-25-1024x905.png 1024w, https://thecodebuzz.com/wp-content/uploads/2019/10/image-25-768x678.png 768w, https://thecodebuzz.com/wp-content/uploads/2019/10/image-25-589x520.png 589w" sizes="auto, (max-width: 1046px) 100vw, 1046px" /></figure>



<p></p>



<p>Happy Coding !!</p>



<p></p>



<p><strong><em>References</em></strong>: </p>



<p></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/static-code-quality-analysis-ndepend/" target="_blank" rel="noreferrer noopener" title="Continuous Code Quality using NDepend"><strong><em>Continuous Code Quality using NDepend</em></strong></a></li>
</ul>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/continuous-code-quality-in-angular-7-applications-using-sonar/" target="_blank" rel="noreferrer noopener" title="Continuous Code Quality of Angular, React, Vue applications using Sonar"><strong><em>Sonar &#8211; Continuous Code Quality of Angular, React, Vue</em></strong></a></li>
</ul>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p><p>The post <a href="https://thecodebuzz.com/middle-man-code-smell-resolution-examples/">Awesome Code – Middle Man Code Smell Resolution with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/middle-man-code-smell-resolution-examples/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Autogenerate C# Class using JSON or JSON Schema</title>
		<link>https://thecodebuzz.com/csharp-class-json-schema/</link>
					<comments>https://thecodebuzz.com/csharp-class-json-schema/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 01 Mar 2022 00:00:00 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[Tips and Guidelines]]></category>
		<category><![CDATA[C# Class using JSON Schema]]></category>
		<category><![CDATA[convert json schema to c# class online]]></category>
		<category><![CDATA[convert json to c# class visual studio]]></category>
		<category><![CDATA[create c# code from json]]></category>
		<category><![CDATA[dynamically generate c# class from json]]></category>
		<category><![CDATA[generate json schema from c# class]]></category>
		<category><![CDATA[Generate JSON Schema from C# Classes]]></category>
		<category><![CDATA[Generate JSON Schema from JSON request]]></category>
		<category><![CDATA[json schema generator]]></category>
		<category><![CDATA[json schema generator c#]]></category>
		<category><![CDATA[json to c#]]></category>
		<category><![CDATA[njsonschema]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=3706</guid>

					<description><![CDATA[<p>Autogenerate C# Class using JSON string or JSON Schema Today in this article, we will see a few techniques of how to autogenerate C# Class using JSON string or JSON Schema. You might find the need for converting JSON schema to C# types or Typescript types while dealing with JSON format. As we know JSON [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/csharp-class-json-schema/">How to Autogenerate C# Class using JSON or JSON Schema</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading"><strong>Autogenerate C# Class using JSON string or JSON Schema</strong></h1>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2019/12/Deserialize-JSON-into-C-type-dynamically-Generics-1024x600.jpg" alt="Auto Generate C# Class using JSON string or JSON Schema" class="wp-image-7235" width="478" height="279" srcset="https://thecodebuzz.com/wp-content/uploads/2019/12/Deserialize-JSON-into-C-type-dynamically-Generics-1024x600.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/12/Deserialize-JSON-into-C-type-dynamically-Generics-300x176.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/12/Deserialize-JSON-into-C-type-dynamically-Generics-768x450.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/12/Deserialize-JSON-into-C-type-dynamically-Generics-785x460.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2019/12/Deserialize-JSON-into-C-type-dynamically-Generics.jpg 1287w" sizes="auto, (max-width: 478px) 100vw, 478px" /></figure>



<p>Today in this article, we will see a few techniques of how to autogenerate C# Class using JSON string or JSON Schema.</p>



<p>You might find the need for converting JSON schema to C# types or Typescript types while dealing with JSON format. </p>



<p>As we know <strong><em>JSON </em></strong>is a very popular format for information exchange, especially when dealing with information exchanges between Microservices using RESTFul principles. </p>



<p></p>



<p>We shall see how we can use <strong>NJsonSchema </strong>a C# library to create C# classes easily. </p>



<p></p>



<p>We will also see <strong>Visual Studio</strong> &#8216;<em>Paste Special</em>&#8216; functionality to achieve the same.</p>



<p>Today in this article, we will cover below aspects,</p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-using-njsonschema-for-creating-classes">Using NJsonSchema for creating classes</a><ul><li><a href="#aioseo-getting-started">Getting started</a></li></ul></li><li><a href="#aioseo-using-visual-studio-to-generate-classes">Using Visual Studio to Generate Classes</a></li><li><a href="#aioseo-summary">Summary</a></li></ul></div>



<p>One can create C# classes for any given JSON in the form of a request or type or schema file. </p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-using-njsonschema-for-creating-classes">Using NJsonSchema for creating classes</h2>



<p></p>



<p><strong>NJsonSchema </strong>is a .NET library to read, generate and validate JSON Schema. It provides basic code generation APIs, which can be used to generate C# classes or <em><strong><a aria-label="generate TypeScript classes or interface (opens in a new tab)" rel="noreferrer noopener" href="https://www.thecodebuzz.com/typescript-classes-using-json-schema/" target="_blank">generate TypeScript classes or interface</a>s</strong></em> from a JSON schema. </p>



<p></p>



<p>The library reads a schema from a file or string and validates JSON data against it. </p>



<p></p>



<p>This library can be used to <strong><em><a aria-label="generate schema from existing .NET classes (opens in a new tab)" href="https://www.thecodebuzz.com/generate-json-schema-from-csharp-classes-and-json-request/" target="_blank" rel="noreferrer noopener">generate a schema from existing .NET classes</a>.</em></strong></p>



<p></p>



<p> Below are a few high-level features about this library, </p>



<p></p>



<ul class="has-medium-font-size wp-block-list"><li> <em><a href="https://www.thecodebuzz.com/generate-json-schema-from-csharp-classes-and-json-request/" target="_blank" rel="noreferrer noopener">Generate C# code from JSON Schema</a></em></li><li><em><a aria-label=" Generate TypeScript code from JSON Schema  (opens in a new tab)" href="https://www.thecodebuzz.com/typescript-classes-using-json-schema/" target="_blank" rel="noreferrer noopener"> Generate TypeScript code from JSON Schema </a></em></li><li><em><a aria-label=" Generate JSON Schema from JSON request or data file (opens in a new tab)" href="https://www.thecodebuzz.com/generate-json-schema-from-csharp-classes-and-json-request/" target="_blank" rel="noreferrer noopener"> Generate JSON Schema from JSON request or data file</a></em></li><li><em> <a aria-label="Generate JSON Schema from .NET classes/type via reflection  (opens in a new tab)" href="https://www.thecodebuzz.com/generate-json-schema-from-csharp-classes-and-json-request/" target="_blank" rel="noreferrer noopener">Generate JSON Schema from .NET classes/type via reflection </a></em></li><li><em> Supports JSON Schema, Swagger and OpenAPI DTO schemas</em></li><li><em> Read existing JSON Schemas and validate JSON data </em></li></ul>



<p></p>



<p>Below the article, we shall see each feature with a simple example.</p>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-getting-started">Getting started</h3>



<p></p>



<p><strong>Create any .NET Core application </strong></p>



<p></p>



<ul class="wp-block-list"><li>Install <strong>Nuget</strong> package,</li></ul>



<p></p>



<p class="has-cyan-bluish-gray-background-color has-background">Install-Package NJsonSchema.CodeGeneration.CSharp -Version 10.1.2</p>



<p></p>



<p>OR </p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="344" src="https://www.thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-1-1024x344.jpg" alt="Autogenerate C# Class using JSON " class="wp-image-7230" srcset="https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-1-1024x344.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-1-300x101.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-1-768x258.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-1-1536x515.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-1-2048x687.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-1-785x263.jpg 785w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p>Please use below schema file to generate the classes. One can use schema or JSON files directly. </p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
{
  &quot;$schema&quot;: &quot;http://json-schema.org/draft-04/schema#&quot;,
  &quot;type&quot;: &quot;object&quot;,
  &quot;properties&quot;: {
    &quot;ID&quot;: {
      &quot;type&quot;: &quot;string&quot;
    },
    &quot;Name&quot;: {
      &quot;type&quot;: &quot;string&quot;
    },
    &quot;City&quot;: {
      &quot;type&quot;: &quot;string&quot;
    },
    &quot;Country&quot;: {
      &quot;type&quot;: &quot;string&quot;
    }
  },
  &quot;required&quot;: &#x5B;
    &quot;ID&quot;,
    &quot;Name&quot;,
    &quot;City&quot;,
    &quot;Country&quot;
  ]
}
</pre></div>


<p></p>



<p>OR</p>



<p></p>



<p>Let&#8217;s use below sample Employee.json file,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
  {
    &quot;ID&quot;: &quot;1002&quot;,
    &quot;Name&quot;: &quot;ABCD&quot;,
    &quot;City&quot;: &quot;city&quot;,
    &quot;Country&quot;: &quot;USA&quot;
  }
</pre></div>


<p></p>



<p>One can write the below logic to generate classes from a given JSON request.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
           string json = File.ReadAllText(&quot;Employee.json&quot;);
            var schemaFromFile = JsonSchema.FromSampleJson(json);
            var classGenerator = new CSharpGenerator(schemaFromFile, new CSharpGeneratorSettings
            {
                ClassStyle = CSharpClassStyle.Poco,
            });
            var codeFile = classGenerator.GenerateFile();
            File.WriteAllText(&quot;C://Test/Employee1.cs&quot;, codeFile);
</pre></div>


<p></p>



<p>The generated files will be saved in the path specified above.</p>



<p>Below is the file generated using the above code,</p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="458" src="https://www.thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-schema-1024x458.jpg" alt="Autogenerate C# Class using JSON " class="wp-image-7231" srcset="https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-schema-1024x458.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-schema-300x134.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-schema-768x344.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-schema-1536x688.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-schema-2048x917.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-schema-785x351.jpg 785w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p><strong>Note: </strong></p>



<p>You might get the below error due to conflicts between Newtonsfot Vs NJSonschema classes. </p>



<p></p>



<p class="has-vivid-red-color has-cyan-bluish-gray-background-color has-text-color has-background">Unable to cast object of type &#8216;Newtonsoft.Json.Schema.JsonSchema&#8217; to type &#8216;NJsonSchema.JsonSchema&#8217;.</p>



<p></p>



<p>Please use the namespace as below to fix the issue,</p>



<p></p>



<p class="has-cyan-bluish-gray-background-color has-background">using JsonSchema = NJsonSchema.JsonSchema;</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-using-visual-studio-to-generate-classes">Using Visual Studio to Generate Classes</h2>



<p></p>



<p>Alternatively, Visual Studio has the “Paste Special” capability to create c# classes from JSON.</p>



<p></p>



<p><strong>Visual Studio &#8211; -&gt; Edit &#8212; &gt; Paste Special </strong></p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-schema-using-Visual-Studio-1024x804.jpg" alt="Create C# Class using JSON string " class="wp-image-7232" width="517" height="405" srcset="https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-schema-using-Visual-Studio-1024x804.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-schema-using-Visual-Studio-300x236.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-schema-using-Visual-Studio-768x603.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-schema-using-Visual-Studio-662x520.jpg 662w, https://thecodebuzz.com/wp-content/uploads/2019/12/C-classes-from-JSON-schema-using-Visual-Studio.jpg 1177w" sizes="auto, (max-width: 517px) 100vw, 517px" /></figure>



<p></p>



<p>The generated class looks as below for the same Employee.json schema,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
public class Rootobject
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}
</pre></div>


<p></p>



<p>Above you need to change a root object to the appropriate name of your choice.</p>



<p></p>



<p>Happy Coding !! </p>



<p></p>



<p><strong><em>Other useful references</em></strong>,</p>



<p></p>



<ul class="wp-block-list" id="block-d510fcdb-ab14-4942-9cc8-16d2d3d74435"><li><strong><em><a href="https://www.thecodebuzz.com/typescript-classes-using-json-schema/" target="_blank" rel="noreferrer noopener">Generate TypeScript code from JSON Schema</a></em></strong></li><li><strong><em><a href="https://www.thecodebuzz.com/generate-json-schema-from-csharp-classes-and-json-request/" target="_blank" rel="noreferrer noopener">Generate JSON Schema from JSON request or data file</a></em></strong></li><li><strong><em><a href="https://www.thecodebuzz.com/generate-json-schema-from-csharp-classes-and-json-request/" target="_blank" rel="noreferrer noopener">Generate JSON Schema from .NET classes/type via reflection</a></em></strong></li></ul>



<p></p>



<h2 class="wp-block-heading" id="aioseo-summary">Summary</h2>



<p></p>



<p>Today in this article, we looked at a few easy techniques for creating C# classes from a given JSON schema. We saw how to use the NJsonSchema CodeGeneration library and also looked at Visual Studio Paste special features to generate required C# types.</p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p> </p><p>The post <a href="https://thecodebuzz.com/csharp-class-json-schema/">How to Autogenerate C# Class using JSON or JSON Schema</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/csharp-class-json-schema/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Configure DbContext in Entity framework ASP.NET Core &#8211; Best Practices</title>
		<link>https://thecodebuzz.com/configure-dbcontext-entity-framework-efcore-asp-net-core/</link>
					<comments>https://thecodebuzz.com/configure-dbcontext-entity-framework-efcore-asp-net-core/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Fri, 04 Jun 2021 14:51:00 +0000</pubDate>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[Tips and Guidelines]]></category>
		<category><![CDATA[asp.net core entity framework database first]]></category>
		<category><![CDATA[asp.net core get dbcontext from services]]></category>
		<category><![CDATA[create dbcontext entity framework core]]></category>
		<category><![CDATA[dbcontext dependency injection .net core]]></category>
		<category><![CDATA[entity framework core code first approach c#]]></category>
		<category><![CDATA[entity framework dbcontext best practices]]></category>
		<category><![CDATA[how to add dbcontext in asp.net core 6]]></category>
		<category><![CDATA[scaffold-dbcontext]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=9864</guid>

					<description><![CDATA[<p>Configure DBContext in Entity framework ASP.NET Core &#8211; Best Practices In this post, we will see how to configure DbContext in Entity framework EFCore in ASP.NET Core. We will see high-level guidelines and best practices that can be considered in general for configuring the DBCOntext. As we looked into our article on Repository implementation for [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/configure-dbcontext-entity-framework-efcore-asp-net-core/">Configure DbContext in Entity framework ASP.NET Core – Best Practices</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading"><strong>Configure DBContext in Entity framework ASP.NET Core &#8211; Best Practices</strong></h1>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="264" src="https://www.thecodebuzz.com/wp-content/uploads/2020/04/What-is-DBContext.-Configuring-a-DbContext-EFCore-1024x264.jpg" alt="Configure DbContext in Entity framework" class="wp-image-9880" srcset="https://thecodebuzz.com/wp-content/uploads/2020/04/What-is-DBContext.-Configuring-a-DbContext-EFCore-1024x264.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/04/What-is-DBContext.-Configuring-a-DbContext-EFCore-300x77.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/04/What-is-DBContext.-Configuring-a-DbContext-EFCore-768x198.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/04/What-is-DBContext.-Configuring-a-DbContext-EFCore-785x202.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/04/What-is-DBContext.-Configuring-a-DbContext-EFCore.jpg 1294w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>In this post, we will see how to configure <strong><em>DbContext </em></strong>in Entity framework EFCore in ASP.NET Core. </p>



<p></p>



<p>We will see high-level guidelines and best practices that can <em><strong>be </strong></em>considered in general for configuring the DBCOntext.</p>



<p></p>



<p>As we looked into our article on <a href="https://www.thecodebuzz.com/entity-framework-repository-implementation-efcore-net-core/" target="_blank" rel="noreferrer noopener" title="Entity Framework Repository Implementation in ASP.NET Core"><em>Repository implementation for Entity framework DbContext</em></a> instance represents the Unit Of Work and Repository patterns that can be used to query from a database and perform CRUD operations.</p>



<p></p>



<p>We shall be covering the below aspects in today&#8217;s article,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-what-is-dbcontext">What is DBContext</a></li><li><a href="#aioseo-configuring-default-database-provider">Configuring the Default Database provider</a></li><li><a href="#aioseo-lifetime-management-of-dbcontext">Lifetime management of DBContext</a></li><li><a href="#aioseo-define-connection-resiliency-for-your-dbcontext">Define Connection Resiliency for your DBContext</a></li><li><a href="#aioseo-concurrency-of-efcore-dbcontext">Concurrency of EFCore DBContext</a></li><li><a href="#aioseo-client-server-query-evaluation">Client-Server query evaluation</a></li><li><a href="#aioseo-summary">Summary</a></li></ul></div>



<p></p>



<p></p>



<div data-schema-only="false" class="wp-block-aioseo-faq" id="aioseo-what-is-dbcontext"><h3 class="aioseo-faq-block-question">What is DBContext</h3><div class="aioseo-faq-block-answer">
<p><strong><em>DBContext </em></strong>represents an abstraction layer around the data we are dealing with. </p>



<p></p>



<p>This abstraction exists between the data and the <strong>Business</strong>/<strong>Domain(DDD) </strong>objects of an application we are dealing with. </p>



<p></p>



<p>It allows you to access everything from the database as an Object (<strong>OOPS</strong>) with simplification and ease</p>



<p></p>



<p><strong><em>DBContext </em></strong>not only isolates the business objects from the database access code but also provides a clean separation of concerns.</p>
</div></div>



<p></p>



<p></p>



<p></p>



<p>Configuring <strong>DbContext </strong>in Entity Framework is important for establishing the connection and performing efficient <strong>CRUD </strong>operations on the datastore of your choice.</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-configuring-default-database-provider">Configuring the Default Database provider</h2>



<p></p>



<p>This shall be the first thing we will do while configuring the <strong><em>DBContext </em></strong>instance. </p>



<p></p>



<p>It should have <strong><em>DbContextOptions </em></strong>which actually help set up required <strong><em>DBContext </em></strong>details along with the database provider to use and connection string etc.</p>



<p></p>



<p>Please do the below configuration to set the <em><strong>DBContext </strong></em>option.</p>



<p></p>



<p>Use <strong><em>AdDbContext</em>()</strong> method to inject the required DBContext injected in the Service <strong>IoC </strong>container as below,</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/04/No-database-provider-has-been-configured-for-this-DbContext-EFCore.jpg" alt="Configure DbContext in Entity framework .NET Core 5 ot .NET 6" class="wp-image-9149" width="566" height="151" srcset="https://thecodebuzz.com/wp-content/uploads/2020/04/No-database-provider-has-been-configured-for-this-DbContext-EFCore.jpg 1025w, https://thecodebuzz.com/wp-content/uploads/2020/04/No-database-provider-has-been-configured-for-this-DbContext-EFCore-300x80.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/04/No-database-provider-has-been-configured-for-this-DbContext-EFCore-768x205.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/04/No-database-provider-has-been-configured-for-this-DbContext-EFCore-785x210.jpg 785w" sizes="auto, (max-width: 566px) 100vw, 566px" /></figure>



<p></p>



<p>Using <strong>DBContext </strong>class to use<strong> Constructor Injections</strong> for the <em><strong>DbContextOptions&lt;TContext&gt;</strong> </em>object as below,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [1]; title: ; notranslate">
 public EmployeeContext(DbContextOptions&lt;EmployeeContext&gt; options)
            : base(options)
        {
        }

        public virtual DbSet&lt;Employee&gt; Employee { get; set; }



..
.
</pre></div>


<p></p>



<p>Similarly, If  using the override <em><strong>OnConfiguring </strong></em>method then you can achieve the same by <em><strong>DBContextOptionsbuilder </strong></em>to initialize the <strong><em>DbContextOption </em></strong>as below,</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/04/InvalidOperationException-No-database-provider-has-been-configured-for-this-DbContext.jpg" alt="Lifetime management of DBContext" class="wp-image-9151" width="539" height="121" srcset="https://thecodebuzz.com/wp-content/uploads/2020/04/InvalidOperationException-No-database-provider-has-been-configured-for-this-DbContext.jpg 1025w, https://thecodebuzz.com/wp-content/uploads/2020/04/InvalidOperationException-No-database-provider-has-been-configured-for-this-DbContext-300x67.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/04/InvalidOperationException-No-database-provider-has-been-configured-for-this-DbContext-768x172.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/04/InvalidOperationException-No-database-provider-has-been-configured-for-this-DbContext-785x176.jpg 785w" sizes="auto, (max-width: 539px) 100vw, 539px" /></figure>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-lifetime-management-of-dbcontext">Lifetime management of DBContext</h2>



<p></p>



<p>Using <em><strong>DbContext </strong></em>with Dependency Injection,</p>



<p></p>



<ul class="wp-block-list">
<li><em>Using</em> DbContext via a dependency injection container is recommended. </li>
</ul>



<p></p>



<p></p>



<ul class="wp-block-list">
<li>This ensures DbContext is created as per request by the <em>API pipeline and disposed of based on lifetime management used while registering it.</em></li>
</ul>



<p></p>



<ul class="wp-block-list">
<li><em>Add the <strong>DbContext </strong>type to the service container by using the <strong>AddDbContext </strong>method with<strong> Scoped lifetime</strong> (<strong>Recommended </strong>).</em></li>
</ul>



<p></p>



<ul class="wp-block-list">
<li><em>Using <strong>AddDbContext</strong>(..) ensures that you are registering the DBCOntext as a <strong>scoped object</strong>. i.e every new request will use the services injected and hence the new DBContext.</em></li>
</ul>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [4,5,6,7,8]; title: ; notranslate">
 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext&lt;EmployeeContext&gt;(options =&gt;
            {
                options.UseSqlServer(Configuration.GetConnectionString(&quot;EmployeeDB&quot;));
            });
        }

</pre></div>


<p></p>



<p>Using <strong><em>DbContext </em></strong>without Dependency Injection,</p>



<p></p>



<p>If not using DI due to some reason, It becomes the implementor’s responsibility to keep track of such resources and dispose of them manually instead of the compiler doing it for you (as we see above using DI).</p>



<p></p>



<p><strong>If not using DI</strong> &#8211; then It&#8217;s recommended to use the &#8220;<strong>Using</strong>&#8221; statement for creating the resources and disposing of them after their usage.</p>



<p></p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [1]; title: ; notranslate">
 using (var context = new EmployeeContext())
            {
                empList = _employeeContext.Employee.AsEnumerable().Select(x =&gt; x.EmployeeId).ToList();
            }
</pre></div>


<p></p>



<p><strong>Access DBContext in Repository or other Services</strong></p>



<p></p>



<p>It&#8217;s better to keep the <em><strong>same lifetime instance for Repository/Other Custom services and DBContext</strong></em> to avoid any issue related to Data corruption.</p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="323" src="https://www.thecodebuzz.com/wp-content/uploads/2020/04/Cannot-access-a-disposed-object.-A-common-cause-of-this-error-is-disposing-a-context-1024x323.jpg" alt="Access DBContext in Repository or other Services" class="wp-image-9875" srcset="https://thecodebuzz.com/wp-content/uploads/2020/04/Cannot-access-a-disposed-object.-A-common-cause-of-this-error-is-disposing-a-context-1024x323.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/04/Cannot-access-a-disposed-object.-A-common-cause-of-this-error-is-disposing-a-context-300x95.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/04/Cannot-access-a-disposed-object.-A-common-cause-of-this-error-is-disposing-a-context-768x242.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/04/Cannot-access-a-disposed-object.-A-common-cause-of-this-error-is-disposing-a-context-785x247.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/04/Cannot-access-a-disposed-object.-A-common-cause-of-this-error-is-disposing-a-context.jpg 1079w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p> </p>



<h2 class="wp-block-heading" id="aioseo-define-connection-resiliency-for-your-dbcontext">Define Connection Resiliency for your DBContext</h2>



<p></p>



<p>The connection resiliency feature retries defaulted database commands automatically. </p>



<p></p>



<p>Use connection resiliency as it just takes a few lines of code for making your connection resilient.</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/04/EnableRetryOnFailure-DBcontext-efcore.jpg" alt="Define Connection Resiliency for your DBContext" class="wp-image-9866" width="478" height="129" srcset="https://thecodebuzz.com/wp-content/uploads/2020/04/EnableRetryOnFailure-DBcontext-efcore.jpg 840w, https://thecodebuzz.com/wp-content/uploads/2020/04/EnableRetryOnFailure-DBcontext-efcore-300x81.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/04/EnableRetryOnFailure-DBcontext-efcore-768x207.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/04/EnableRetryOnFailure-DBcontext-efcore-785x211.jpg 785w" sizes="auto, (max-width: 478px) 100vw, 478px" /></figure>



<p></p>



<p>For more details: <a rel="noreferrer noopener" href="https://www.thecodebuzz.com/database-connection-resiliency-entity-framework-asp-net-core/" target="_blank"><strong><em>Database Connection Resiliency in Entity Framework ASP.NET Core</em></strong></a></p>



<p></p>



<p>If dealing with multiple <em><strong>DBContext, then Connection resiliency</strong></em> needs to be defined per <em>DBContext</em> separately.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-concurrency-of-efcore-dbcontext"><strong>Concurrency of EFCore DBContext</strong></h2>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>DBContext object is not thread-safe.</strong></p>
</blockquote>



<p></p>



<p>Using <strong>AddDbContext(..)</strong> however, ensures that you are registering the DBContext as Scoped. i.e every new request will use the new service instance and hence the new DBContext. </p>



<p></p>



<p>So ideally concurrency is implemented per request basic avoiding any data corruption issues.</p>



<p></p>



<p>However, It should be protected from any parallel access within the same request context. </p>



<p></p>



<p>It&#8217;s the implementor’s responsibility to implement the concurrency while using it in<strong><em> Task/Multithreaded</em></strong> operations.</p>



<p></p>



<p>As good practice also please make sure to use <a href="https://www.thecodebuzz.com/understanding-async-and-await-api-asynchronous-programming/" target="_blank" rel="noreferrer noopener" title="Understanding Async and Await API – Asynchronous Programming"><em><strong>Synchronous and Asynchronous operation</strong></em></a> properly in the code.</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/04/A-second-operation-started-on-this-context-before-a-previous-operation-completed-efcore-issue-1024x519.jpg" alt="Concurrency of EFCore DBContext" class="wp-image-9876" width="483" height="244" srcset="https://thecodebuzz.com/wp-content/uploads/2020/04/A-second-operation-started-on-this-context-before-a-previous-operation-completed-efcore-issue-1024x519.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/04/A-second-operation-started-on-this-context-before-a-previous-operation-completed-efcore-issue-300x152.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/04/A-second-operation-started-on-this-context-before-a-previous-operation-completed-efcore-issue-768x389.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/04/A-second-operation-started-on-this-context-before-a-previous-operation-completed-efcore-issue-785x398.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/04/A-second-operation-started-on-this-context-before-a-previous-operation-completed-efcore-issue.jpg 1360w" sizes="auto, (max-width: 483px) 100vw, 483px" /></figure>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>In the above code, I marked <a href="https://www.thecodebuzz.com/?p=22705">method a method call</a> with <em><strong>await </strong></em>as it invokes an Asynchronous operation. For more details please refer <a href="https://www.thecodebuzz.com/understanding-async-and-await-api-asynchronous-programming/" target="_blank" rel="noreferrer noopener" title="Understanding Async and Await API – Asynchronous Programming"><em><strong>Understanding Async vs Sync programming</strong></em></a></p>
</blockquote>



<p></p>



<h2 class="wp-block-heading" id="aioseo-client-server-query-evaluation">Client-Server query evaluation</h2>



<p></p>



<p>.NET Core 3.0 onwards Entity Framework Core has blocked <a href="https://www.thecodebuzz.com/query-linq-evaluation-in-entity-framework-guidelines/" target="_blank" rel="noreferrer noopener">client-side query evaluation</a> and recommends query execution on the server only.</p>



<p></p>



<p><strong>If using the older version(&lt;3.0)</strong> of EF Core please let the developer know about query evaluation support. One can configure the below warning for the same,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(sqlConnectionString,
                 builder =&gt; builder.EnableRetryOnFailure())
                 .ConfigureWarnings(warnings =&gt; warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));

            }

</pre></div>


<p></p>



<p>Or the same can be configured within <strong><em>Configure </em></strong>method in the <strong><em>StartUp.cs </em></strong></p>



<p></p>



<p><strong><em>Other references :</em></strong></p>



<p></p>



<ul class="wp-block-list">
<li><strong><em><a href="https://www.thecodebuzz.com/database-connection-resiliency-entity-framework-asp-net-core/" target="_blank" rel="noreferrer noopener">Connection Resiliency Using EnableRetry and Execution Strategy- PartI</a></em></strong></li>
</ul>



<ul class="wp-block-list">
<li><strong><em><a href="https://www.thecodebuzz.com/getting-started-efcore-entity-framework-core-orm-asp-net-core/" target="_blank" rel="noreferrer noopener">Getting Started with EFCore in ASP.NET Core</a></em></strong></li>
</ul>



<p></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-summary">Summary</h2>



<p></p>



<p>Today in this article we looked at guidelines around configuring the <strong><em>DBContext </em></strong>in Entity framework ASP.NET Core applications. We looked at various aspects like managing database providers, lifetime management, resiliency, and concurrency management while configuring the <em><strong>DBContext</strong></em>.</p>



<p></p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p> </p>



<p></p><p>The post <a href="https://thecodebuzz.com/configure-dbcontext-entity-framework-efcore-asp-net-core/">Configure DbContext in Entity framework ASP.NET Core – Best Practices</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/configure-dbcontext-entity-framework-efcore-asp-net-core/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
	</channel>
</rss>
