• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Friday, August 7, 2020

Entity State in Entity Framework

 Admin     August 07, 2020     .Net, C#, Entity Framework     No comments   

In this article, I will discuss the Entity State in Entity Framework. The Entity state represents the state of an entity. An entity is always in any one of the following states.
  1. Added: The entity is marked as added.
  2. Deleted: The entity is marked as deleted.
  3. Modified: The entity has been modified.
  4. Unchanged: The entity hasn’t been modified
  5. Detached: The entity isn’t tracked.
EF maintains the state of each entity during its lifetime. Each entity has a state based on the operation performed on it via the context class (the class which is derived from DbContext class). The entity state represented by an enum i.e. System.Data.Entity.EntityState has the following values.
Entity State in Entity Framework

The Context not only holds the reference to all the entity objects as soon as retrieved from the database but also keeps track of entity states and maintains modifications made to the properties of the entity. This feature is known as Change Tracking.

State Changes in the Entity Lifecycle
The change in the entity state from the Unchanged to the Modified state is the only state that’s automatically handled by the context class. All other changes must be made explicitly by using proper methods of DbContext class.

The following diagram shows the different states of an entity in Entity Framework.
Entity State in Entity Framework

Let’s discuss different states.

Unchanged State
The property values of the entity have not been modified since it was retrieved from the database. SaveChanges ignores this entity.

This is the default state the entities will be in when we perform the query and also whenever we attach an entity to the context using Attach() method.

Detached State
Whenever we use Detach() method, the entity will be in the Detached state. Once the entity is in the Detached state, it cannot be tracked by the ObjectContext. We have to use Attach() method for the entity to be tracked by the ObjectContext.

The Detached entity state indicates that the entity is not being tracked by the context.

Added State
Whenever we add a new entity to the context using the AddObject() method, the state of the entity will be in the Added state.

Added entity state indicates that the entity exists in the context, but does not exist in the database. DbContext generates the INSERT SQL query and insert the data into the database when the saveChanges method is invoked. Once the saveChanges are successful the state of the entity is changed to Unchanged

Modified State:
The entity will be in a Modified state whenever we modify scalar properties.

The Modified entity state indicates that the entity is modified but not updated in the database. It also indicates that the entity exists in the database. The Dbcontext generates the update SQL Query to remove the entity from the database. Once the saveChanges is successful the state of the entity is changed to Unchanged

In the Connected environment, the Entity framework also keeps track of the properties that have been modified. The Columns in the Update statement are set for only those columns, whose values are modified.

Deleted State
Whenever we call the DeleteObject() method, the entity will be deleted from the context and will be marked as “Deleted”. When the SaveChanges method is called, the corresponding rows are deleted from the database.

The Deleted entity state indicates that the entity is marked for deletion, but not yet deleted from the database. It also indicates that the entity exists in the database. The DbContext generates the delete SQL Query to remove the entity from the database. The entity is removed from the context once the delete operation succeeds after the saveChanges

Thus, entity states play an important role in Entity Framework. We will discuss all these entity states with the example in our upcoming articles.

In the next article, I will discuss in which environment which approach we need to follow.

In this article, I try to explain the Entity States in Entity Framework. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article

Summary:
I hope this post will be helpful to understand the concept of Entity State in Entity Framework
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Entity Types in Entity Framework

 Admin     August 07, 2020     .Net, C#, Entity Framework     No comments   

In this article, I am going to discuss the Entity Types in Entity Framework in detail. Please read our previous article where we discussed Entities in Entity Framework with an example. At the end of this article, you will understand the Different Types of Entities in Entity Framework and their use with examples.

Types of Entities in Entity Framework:
In Entity Framework, there are two types of entities that allow developers to use their own custom data classes together with the data model without making any modifications to the data classes themselves. The two types of Entities are as follows:
  1. POCO entities
  2. Dynamic Proxy entities
POCO Entities
POCO stands for Plain Old CLR Objects which can be used as existing domain objects with your data model. The POCO data classes which are mapped to entities are defined in a data model. A POCO entity is a class that doesn’t depend on any framework-specific base class. It is like any other normal .NET CLR class, which is why it is called “Plain Old CLR Objects”. The POCO entities are supported in both EF 6 and EF Core.

These POCO entities support most of the same query, insert, update, and delete behaviors as entity types that are generated by the Entity Data Model. The following is an example of an Employee POCO entity.
public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Gender { get; set; }
    public Nullable<int> Salary { get; set; }
    public Nullable<int> DepartmentId { get; set; }
    public virtual Department Department { get; set; }
}
Dynamic Proxy Entities
The Dynamic Proxy is a runtime proxy class that wraps the POCO entity. Dynamic proxy entities allow lazy loading.
  1. A POCO entity should meet the following requirements to become a POCO proxy:
  2. The POCO class must be declared with public access.
  3. A POCO class must not be sealed.
  4. The POCO class must not be abstract.
  5. Each navigation property must be declared as public, virtual.
  6. All the collection property must be ICollection.
  7. The ProxyCreationEnabled option must NOT be false (default is true) in context class.
Note: Dynamic proxy entities are only supported in EF 6. EF Core 2.0 does not support them yet.

The following POCO entity meets all of the above requirements to become a dynamic proxy entity at runtime.
public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Gender { get; set; }
    public Nullable<int> Salary { get; set; }
    public Nullable<int> DepartmentId { get; set; }
    public virtual Department Department { get; set; }
}
Get the Entity Type from the Proxy Type:
We can find the original or actual entity type from this proxy type using the GetObjectType method of ObjectContext. This is a static method so there is no need to create an object of the object context.
namespace EFDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EF_Demo_DBEntities DBEntities = new EF_Demo_DBEntities())
            {
                var employee = DBEntities.Employees.Find(1);
                var employeeType = ObjectContext.GetObjectType(employee.GetType());       
                Console.WriteLine("FullName of Employee Master Type :" + employeeType.FullName);
                Console.ReadKey();
            }
        }
    }
}
The GetObjectType returns an actual entity type even if we pass the instance of entity type (not the proxy type). In short, we can always use this method to get the actual entity type, there is no need to check whether the type is a proxy type or not.

Note: By default, the dynamic proxy is enabled for every entity. However, you can disable dynamic proxy in the context by setting this.Configuration.ProxyCreationEnabled = false; as shown below
namespace EFDemo
{
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    public partial class EF_Demo_DBEntities : DbContext
    {
        public EF_Demo_DBEntities()
            : base("name=EF_Demo_DBEntities")
        {
            this.Configuration.ProxyCreationEnabled = false;
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
        
        public virtual DbSet<Department> Departments { get; set; }
        public virtual DbSet<Employee> Employees { get; set; }
    }
}
In the next article, I am going to discuss the Entity States in Entity Framework. Here, in this article, I try to explain Entity Types in Entity Framework. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article

Summary:
I hope this post will be helpful to understand the concept of Entity Types in Entity Framework
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Entities in Entity Framework

 Admin     August 07, 2020     .Net, C#, Entity Framework     No comments   

In this article, I am going to discuss Entities in Entity Framework with examples. Please read our previous article where we discussed Entity Framework Context Class in Detail. At the end of this article, you will understand what exactly an entity is and when and how to use Entities in Entity Framework.

What is an Entity in Entity Framework?
An entity in Entity Framework is a class in our application which is included as a DbSet type property in the derived context class. Entity Framework maps each entity to a table and each property of an entity to a column in the database.

We are going to work with the same example, that we worked in our previous article. Let’s see the Solution of the console application that we created in Introduction to Entity Framework article of this article series.
Entities in Entity Framework

The following Department and Employee classes are domain classes in this application.
namespace EFDemo
{
    using System;
    using System.Collections.Generic;
    
    public partial class Department
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Department()
        {
            this.Employees = new HashSet<Employee>();
        }
    
        public int ID { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Employee> Employees { get; set; }
    }
}
namespace EFDemo
{
    using System;
    using System.Collections.Generic;
    
    public partial class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Gender { get; set; }
        public Nullable<int> Salary { get; set; }
        public Nullable<int> DepartmentId { get; set; }
    
        public virtual Department Department { get; set; }
    }
}
The above Department and Employee classes become entities when they have included as DbSet properties in the context class (the class which is derived from DbContext Class).

Let’s open the EF_Demo_DBEntities.cs class which is a context class which is looks like below
namespace EFDemo
{
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    public partial class EF_Demo_DBEntities : DbContext
    {
        public EF_Demo_DBEntities()
            : base("name=EF_Demo_DBEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<Department> Departments { get; set; }
        public virtual DbSet<Employee> Employees { get; set; }
    }
}
In the above context class Departments and Employees, properties are of type DbSet which are called entity sets. The Departments and Employees are entities. An Entity can include two types of properties: Scalar Properties and Navigation Properties.

Scalar Property:
The primitive type properties are called scalar properties. Scalar property stores the actual data. A scalar property maps to a single column in the database table. For example: in Employee class below are the scalar properties
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Gender { get; set; }
public Nullable<int> Salary { get; set; }
public Nullable<int> DepartmentId { get; set; }
In Department Class Below are the Scalar properties
public int ID { get; set; }
public string Name { get; set; }
public string Location { get; set; }
Navigation Property:
The navigation property represents a relationship to another entity. There are two types of navigation properties:
  1. Reference Navigation
  2. Collection Navigation
Reference Navigation Property:
If an entity includes a property of entity type, it is called a Reference Navigation Property. It represents the multiplicity of one (1). For example: In Employee Class below property is a Reference Navigation property.

public virtual Department Department { get; set; }

Collection Navigation Property:
If an entity includes a property of collection type, it is called a collection navigation property. It represents the multiplicity of many (*). For example: In Department class below the property is a collection navigation property.

public virtual ICollection Employees { get; set; }

In the next article, I am going to discuss Types of entities in Entity Framework. Here, in this article, I try to explain Entities in Entity Framework with one example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article

Summary:
I hope this post will be helpful to understand the concept of Entities in Entity Framework
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Entity Framework Context Class

 Admin     August 07, 2020     .Net, C#, Entity Framework     No comments   

In this article, I am going to discuss the Entity Framework Context Class with an example. Please read our previous article where we discussed the Architecture of Entity Framework in Detail. At the end of this article, you will understand what exactly the Context Class is and when and how to use this Context Class in Entity Framework with an example.

What is Context Class in Entity Framework?
The Entity Framework enables us to query, insert, update, and delete data using Common Language Runtime (CLR) objects which are also known as entities. The Entity Framework maps the entities and relationships that are defined in our model to a database.

The primary class that is responsible for interacting with data as objects is System.Data.Entity.DbContext. The context class in Entity Framework is a class that derives from DBContext in EF 6 and EF Core both. It is an important class in Entity Framework, which represents a session with the underlying database.

We are going to work with the same example that we created in our Introduction to Entity Framework article. In that console application, we retrieve the data from a SQL Server database using Entity Framework.

First, let’s have a look at the solution. Please double click on the EF_Demo_DBEntities which is inside the EmployeeDataModel.Context.cs which is inside EmployeeDataModel.Context.tt file as shown below.
Entity Framework Context Class

The following EF_Demo_DBEntities class is an example of a context class which is created by Entity Framework.
namespace EFDemo
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    
    public partial class EF_Demo_DBEntities : DbContext
    {
        public EF_Demo_DBEntities()
            : base("name=EF_Demo_DBEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<Department> Departments { get; set; }
        public virtual DbSet<Employee> Employees { get; set; }
    }
}
In the above example, the EF_Demo_DBEntities class is derived from the DbContext class which makes it a context class. It also includes an entity set for Departments and Employees entities.

The context class is used to query or save data to the database. It is also used to configure domain classes, database-related mappings, change tracking settings, caching, transaction, etc. which we will discuss in detail in our upcoming articles.

How to query using Context Class?
Modify the Program class as shown below.
namespace EFDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EF_Demo_DBEntities DBEntities = new EF_Demo_DBEntities())
            {
                List<Department> listDepartments = DBEntities.Departments.ToList();
                Console.WriteLine();
                foreach(Department dept in listDepartments)
                {
                    Console.WriteLine("  Department = {0}, Location = {1}", dept.Name, dept.Location);
                    foreach(Employee emp in dept.Employees)
                    {
                        Console.WriteLine("\t Name = {0}, Email = {1}, Gender = {2}, salary = {3}",
                            emp.Name, emp.Email, emp.Gender, emp.Salary);
                    }
                    Console.WriteLine();
                }
                Console.ReadKey();
            }
        }
    }
}
Run the application and see the results. We will discuss more the Context class in a later article.

In the next article, I am going to discuss the Entities in Entity Framework. Here, in this article, I try to explain the Context class in Entity Framework with one example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article

Summary:
I hope this post will be helpful to understand the Entity Framework Context Class
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Entity Framework Architecture

 Admin     August 07, 2020     .Net, C#, Entity Framework     No comments   

In this article, I am going to discuss the Entity Framework Architecture in Detail. Please read our previous article where we discussed the Overview of the Entity Framework. At the end of this article, you will understand the following pointers in detail.
  1. What is Entity Framework?
  2. The Architecture of Entity Framework.
  3. Understanding the different components of the Entity Framework.
  4. How the Entity Framework works?
What is Entity Framework?
As we already discussed in our previous article, the Entity Framework is an object-relational mapper (O/RM) that enables .NET developers to work with a database using .NET objects. It eliminates the need for most of the data-access code that developers usually need to write.

Entity Framework Architecture
The Architecture of Entity Framework is composed of the following components
  1. The Entity Data Model
  2. LINQ to Entities
  3. Entity SQL
  4. The Object Services Layer
  5. Entity Client data provider
  6. ADO.Net Data Provider
The following diagram shows the overall architecture of the Entity Framework.
Entity Framework Architecture

Let’s discuss each of the components of the Entity framework architecture in detail.

EDM (Entity Data Model):
The Entity Data Model (EDM) abstracts the logical or the relational schema and exposes the conceptual schema of the data using a three-layered approach i.e.
  1. The conceptual model (C- Space),
  2. Mapping model (C-S Space)
  3. Storage model (S – Space)
Conceptual Model:
The conceptual model contains the model classes (i.e. entities) and their relationships. This will be independent of your database table design. It defines your business objects and their relationships in XML files.

Mapping Model:
A Mapping Model consists of information about how the conceptual model is mapped to the storage model. The Mapping model is responsible for mapping the conceptual and logical layers (Storage layer). It maps the business objects and the relationships defined in the conceptual layer with the tables and relationships defined in the logical layer.

Storage Model / Logical Model:
The storage model represents the schema of the underlying database. That means the storage model is the database design model which includes tables, views, Keys, stored procedures, and their relationships.

The Entity Data Model uses the following three types of XML files to represent the C-Space, C-S Space, and the S-Space respectively.
  1. .CSDL (Conceptual Schema Definition Language): This represents the C-S Space and is used to map the entity types used in the conceptual model.
  2. .MSL (Mapping Schema Language): This represents the C-S Space and is used to map the logical model to the conceptual model.
  3. .SSDL (Store Schema Definition Language): This represents the S-Space and is used to map the schema information of the logical layer.
LINQ to Entities:
LINQ-to-Entities (L2E) is a query language used to write queries against the object model. It returns entities, which are defined in the conceptual model. You can use your LINQ skills here.

Entity SQL:
Entity SQL is another query language (For EF 6 only) just like LINQ to Entities. However, it is a little more difficult than LINQ-to-Entities (L2E) and the developer will have to learn it separately. These E-SQL queries are internally translated to data store dependent SQL queries. The conversion of the E-SQL queries to their datastore-specific query language like T-SQL is handled by the Entity Framework.

Object Service:
In a real-time scenarios, most of the time we might have to work with entities such as in-memory objects or a collection of in-memory objects. To do this we need Object Services. We can use it to query data, from almost all data stores, with less code.

Object Services layer is the Object Context, which represents the session of interaction between the applications and the data source.
  1. The main use of the Object Context is to perform different operations like add, update and delete instances of entities and to save the changed state back to the database with the help of queries.
  2. It is the ORM layer of Entity Framework, which represents the data result to the object instances of entities.
  3. This service allows the developer to use some of the rich ORM features like primary key mapping, change tracking, etc. by writing queries using LINQ and Entity SQL.
Apart from this, the Object Services Layer provides the following additional services:
  1. Change tracking
  2. Lazy loading
  3. Inheritance
  4. Optimistic concurrency
  5. Merging data
  6. Identity resolution
  7. Support for querying data using Entity SQL and LINQ to Entities
  8. We will discuss on Object services Layer in detail, in our upcoming articles.
Entity Client Data Provider:
The main responsibility of this layer is to convert LINQ-to-Entities or Entity SQL queries into a SQL query which is understood by the underlying database. It communicates with the ADO.Net data provider which in turn sends or retrieves data from the database.

ADO.Net Data Provider:
This layer communicates with the database using standard ADO.Net.

In the next article, I am going to discuss the Context Class in Entity Framework with an example. Here, in this article, I try to explain the Entity Framework Architecture in Details. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Summary:
I hope this post will be helpful to understand Entity Framework Architecture
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Introduction to Entity Framework

 Admin     August 07, 2020     .Net, C#, Entity Framework     No comments   

Before .NET 3.5 as a developer, we often used to write ADO.NET code to perform CRUD operation with the underlying database. For this, we need to create a connection with the database, open the connection, create a DataSet to fetch or submit the data to the database, and convert the data from the DataSet to .NET objects or vice-versa to apply our business rules. Actually, this was a time consuming, cumbersome, and error-prone process. Microsoft has provided a framework called “Entity Framework” to automate all these database related activities for our application if we provided the necessary details to the Entity Framework. In this article, I will give a brief Introduction to Entity Framework.

What is Entity Framework?
Entity Framework is an open-source object-relational mapping (ORM) Framework for .NET applications that enables .NET developers to work with relational data using domain-specific objects without focusing on the underlying database tables and columns where actually the data is stored. That means the Entity Framework eliminates the need for writing the data-access code that developers usually need to write.

Official Definition: “Entity Framework is an object-relational mapper (O/RM) that enables .NET developers to work with a database using .NET objects. It eliminates the need for most of the data-access code that developers usually need to write.”

What is the Object-Relational Mapping Framework?
Object Relational Mapping framework automatically creates classes based on database tables, and the vice versa is also true, that is, it can also automatically generate the necessary SQL to create database tables based on classes.

The following diagram illustrates where the Entity Framework fits into our application.
Introduction to Entity Framework

The above diagram states Entity Framework fits between the business entities (i.e. the domain classes) and the database. It saves the data in the database stored in the properties of the business entities (domain classes) and also retrieves the data from the database and converts it to business entities objects automatically.

Let’s understand what entity framework can do for us with an example.
Assume we have the following 2 tables
Introduction to Entity Framework

Introduction to Entity Framework

We want to display the above data from both the tables in a console application as shown below.
Introduction to Entity Framework

To achieve this
  1. We need to create Department and Employee classes
  2. We need to write ADO.NET code to retrieve the data from the database
  3. Once the data is retrieved we need to create Department and Employee objects and populate them with the retrieved data.
But Entity Framework can do all of the above automatically if we provide the necessary database schema to the Entity Framework.

Step1: Use below SQL script to create the database, tables and populate the tables with some test data
IF EXISTS (SELECT * FROM sys.databases WHERE name = 'EF_Demo_DB')
  DROP DATABASE EF_Demo_DB;
GO
-- Create the School database.
CREATE DATABASE EF_Demo_DB;
GO
-- Specify a simple recovery model 
-- to keep the log growth to a minimum.
ALTER DATABASE EF_Demo_DB 
  SET RECOVERY SIMPLE;
GO
USE EF_Demo_DB;
GO
-- Create Departments table
CREATE TABLE Departments
(
     ID INT PRIMARY KEY IDENTITY(1,1),
     Name VARCHAR(50),
     Location VARCHAR(50)
)
Go
-- Create Employees table.
CREATE TABLE Employees
(
     ID INT PRIMARY KEY IDENTITY(1,1),
     Name VARCHAR(50),
     Email VARCHAR(50),
     Gender VARCHAR(50),
     Salary INT,
     DepartmentId INT FOREIGN KEY REFERENCES Departments(ID)
)
Go
--Populate the Departments table with some test data
INSERT INTO Departments VALUES ('IT', 'Mumbai')
INSERT INTO Departments VALUES ('HR', 'Delhi')
INSERT INTO Departments VALUES ('Sales', 'Hyderabad')
Go
--Populate the Employees table with some test data
INSERT INTO Employees VALUES ('Mark', 'Mark@g.com', 'Male', 60000, 1)
INSERT INTO Employees VALUES ('Steve', 'Steve@g.com', 'Male', 45000, 3)
INSERT INTO Employees VALUES ('Pam', 'Pam@g.com', 'Female', 60000, 1)
INSERT INTO Employees VALUES ('Sara', 'Sara@g.com', 'Female', 345000, 3)
INSERT INTO Employees VALUES ('Ben', 'Ben@g.com', 'Male', 70000, 1)
INSERT INTO Employees VALUES ('Philip', 'Philip@g.com', 'Male', 45000, 2)
INSERT INTO Employees VALUES ('Mary', 'Mary@g.com', 'Female', 30000, 2)
INSERT INTO Employees VALUES ('Valarie', 'Valarie@g.com', 'Female', 35000, 3)
INSERT INTO Employees VALUES ('John', 'John@g.com', 'Male', 80000, 1)
Go
Step2: Create a new “Console Application” with name = EFDemo as shown below
Introduction to Entity Framework

Step 3: adding ADO.NET Entity Data Model Right-click on the project in solution explorer and select Add => New Item, and then click on Data Section from the left side panel and choose ADO.NET Entity Data Model middle panel, Change the name from Model1 to EmployeeDataModel as shown below.
Introduction to Entity Framework

Once we click on the Add button it will open Choose Data Model wizard as shown below.
Introduction to Entity Framework

From this window select EF Designer from the database and click on the Next button which will open choose your data connection wizard as shown below.
Introduction to Entity Framework

In this window first, click on New Connection which will open a popup for providing the database details as shown below.
Introduction to Entity Framework

From this connection properties screen,
  1. Select “Microsoft SQL Server” as Data source, and “.Net Framework Data Provider for SQL Server” option from the “Data provider” drop-down list. Click Continue.
  2. On the “Connection Properties” screen, specify SQL Server Name.
  3. Specify the Authentication you want to use.
  4. Select the database from “Select or enter a database name” drop-down list.
  5. Finally “Test connection” and click “OK”
At this point, we should be back on to the “Choose Your Data Connection” window. Make sure “Save entity connection settings in App.Config as” checkbox is selected and change the name of the connection string to EF_Demo_DBEntities and then Click “Next” button as shown below
Introduction to Entity Framework

Once we click on the Next button it will open a popup asking you to choose the Entity Framework version as shown below.
Introduction to Entity Framework

From this window select Entity Framework 6.x and click on the Next button which will open Choose Your Database Objects as shown below.
Introduction to Entity Framework

On this “Choose Your Database Objects” screen, select “Departments” and “Employees” tables. Change the Model Namespace to “EmployeeModel” and click the “Finish” button. At this point, you should have EmployeeDataModel.edmx created.
Introduction to Entity Framework

The following is the structure of our edmx file.
Introduction to Entity Framework

The Entity Framework Create Employee and Department classes automatically based on the Employees and Departments Tables. Tables are mapped to classes and columns are mapped to class properties.

Now copy and paste the following code in the main method of program class as shown below
namespace EFDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EF_Demo_DBEntities DBEntities = new EF_Demo_DBEntities())
            {
                List<Department> listDepartments = DBEntities.Departments.ToList();
                Console.WriteLine();
                foreach(Department dept in listDepartments)
                {
                    Console.WriteLine("  Department = {0}, Location = {1}", dept.Name, dept.Location);
                    foreach(Employee emp in dept.Employees)
                    {
                        Console.WriteLine("\t Name = {0}, Email = {1}, Gender = {2}, salary = {3}",
                            emp.Name, emp.Email, emp.Gender, emp.Salary);
                    }
                    Console.WriteLine();
                }
                Console.ReadKey();
            }
        }
    }
}
Run the application and notice that Departments and Employees data are displayed as expected. We have achieved all this without writing a single line of ado.net code.

If this is not clear at this moment how it works, then don’t worry we will discuss each and everything in detail in our upcoming articles.

Entity Framework Features:
Cross-platform: EF Core is a cross-platform framework which means it can run on Windows, Linux, and Mac operating systems.

Modeling: EF (Entity Framework) creates an EDM (Entity Data Model) based on POCO (Plain Old CLR Object) entities with get/set properties of different data types. It uses this model also when querying or saving entity data to the underlying database.

Querying: EF allows us to use LINQ queries (C#/VB.NET) to retrieve data from the underlying database. The database provider will translate these LINQ queries into the database-specific query language (e.g. SQL for a relational database). EF also allows us to execute raw SQL queries directly to the database.

Change Tracking: EF keeps track of changes that occurred to instances of our entities (Property values) that need to be submitted to the database.

Saving: EF executes INSERT, UPDATE, and DELETE commands to the database based on the changes that occurred to our entities when we call the SaveChanges() method. EF also provides the asynchronous SaveChangesAsync() method.

Concurrency: EF uses Optimistic Concurrency by default to protect overwriting changes made by another user since data was fetched from the database.

Transactions: EF performs automatic transaction management while querying or saving data. It also provides options to customize transaction management.

Caching: EF includes the first level of caching out of the box. So, repeated querying will return data from the cache instead of hitting the database.

Built-in Conventions: EF follows conventions over the configuration programming pattern, and includes a set of default rules which automatically configure the EF model.

Configurations: EF allows us to configure the EF model by using data annotation attributes or Fluent API to override default conventions.

In the next article, I will discuss the Architecture of the Entity Framework.

In this article, I try to explain Introduction to Entity Framework with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article

Summary:
I hope this post will be helpful to understand the Introduction to Entity Framework
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Wednesday, August 5, 2020

Recursion And Back Tracking

 Admin     August 05, 2020     Algorithm, Data Structure     No comments   

In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Theorem. In this article, we will look at one of the important topics, “recursion”, which will be used in almost every chapter, and also its relative “backtracking”.

What is Recursion?
Any function which calls itself is called recursive. A recursive method solves a problem by calling a copy of itself to work on a smaller problem. This is called the recursion step. The recursion step can result in many more such recursive calls.

It is important to ensure that the recursion terminates. Each time the function calls itself with a slightly simpler version of the original problem. The sequence of smaller problems must eventually converge on the base case.

Why Recursion?
Recursion is a useful technique borrowed from mathematics. Recursive code is generally shorter and easier to write than iterative code. Generally, loops are turned into recursive functions when they are compiled or interpreted.

Recursion is most useful for tasks that can be defined in terms of similar sub-tasks. For example, sort, search, and traversal problems often have simple recursive solutions.

Format of a Recursive Function
A recursive function performs a task in part by calling itself to perform the subtasks. At some point, the function encounters a subtask that it can perform without calling itself. This case, where the function does not recur, is called the base case. The former, where the function calls itself to perform a subtask, is referred to as the recursive case. We can write all recursive functions using the format:
Recursion And Back Tracking

As an example consider the factorial function: n! is the product of all integers between n and 1.The definition of recursive factorial looks like:
Recursion And Back Tracking

This definition can easily be converted to recursive implementation. Here the problem is determining the value of n!, and the subproblem is determining the value of (n – l)!. In the recursive case, when n is greater than 1, the function calls itself to determine the value of (n – l)! and multiplies that with n.

In the base case, when n is 0 or 1, the function simply returns 1. This looks like the following:
Recursion And Back Tracking

Recursion and Memory (Visualization)
Each recursive call makes a new copy of that method (actually only the variables) in memory. Once a method ends (that is, returns some data), the copy of that returning method is removed from memory. The recursive solutions look simple but visualization and tracing take time. For better understanding, let us consider the following example.
Recursion And Back Tracking

For this example, if we call the print function with n=4, visually our memory assignments may look like:
Recursion And Back Tracking

Now, let us consider our factorial function. The visualization of factorial function with n=4 will look like:
Recursion And Back Tracking

Recursion versus Iteration
While discussing recursion, the basic question that comes to mind is: which way is better? –iteration or recursion? The answer to this question depends on what we are trying to do. A recursive approach mirrors the problem that we are trying to solve. A recursive approach makes it simpler to solve a problem that may not have the most obvious of answers. But, recursion adds overhead for each recursive call (needs space on the stack frame).

Recursion
  1. Terminates when a base case is reached.
  2. Each recursive call requires extra space on the stack frame (memory).
  3. If we get infinite recursion, the program may run out of memory and result in stack overflow.
  4. Solutions to some problems are easier to formulate recursively.
Iteration
  1. Terminates when a condition is proven to be false.
  2. Each iteration does not require extra space.
  3. An infinite loop could loop forever since there is no extra memory being created.
  4. Iterative solutions to a problem may not always be as obvious as a recursive solution.
Notes on Recursion
  1. Recursive algorithms have two types of cases, recursive cases, and base cases.
  2. Every recursive function case must terminate at a base case.
  3. Generally, iterative solutions are more efficient than recursive solutions [due to the overhead of function calls].
  4. A recursive algorithm can be implemented without recursive function calls using a stack, but it’s usually more trouble than its worth. That means any problem that can be solved recursively can also be solved iteratively.
  5. For some problems, there are no obvious iterative algorithms.
  6. Some problems are best suited for recursive solutions while others are not.
Example Algorithms of Recursion
  1. Fibonacci Series, Factorial Finding
  2. Merge Sort, Quick Sort
  3. Binary Search
  4. Tree Traversals and many Tree Problems: InOrder, PreOrder PostOrder
  5. Graph Traversals: DFS [Depth First Search] and BFS [Breadth First Search]
  6. Dynamic Programming Examples
  7. Divide and Conquer Algorithms
  8. Towers of Hanoi
  9. Backtracking Algorithms [we will discuss in the next section]
Recursion: Problems & Solutions
In this chapter, we cover a few problems with recursion and we will discuss the rest in other chapters. By the time you complete reading the entire book, you will encounter many recursion problems.

Problem-1 Discuss Towers of Hanoi puzzle.
Solution: The Towers of Hanoi is a mathematical puzzle. It consists of three rods (or pegs or towers), and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks on one rod in ascending order of size, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, satisfying the following rules:
  1. Only one disk may be moved at a time.
  2. Each move consists of taking the upper disk from one of the rods and sliding it onto
another rod, on top of the other disks that may already be present on that rod. No disk may be placed on top of a smaller disk.

Algorithm:
  1. Move the top n – 1 disk from Source to Auxiliary tower,
  2. Move the nth disk from Source to Destination tower,
  3. Move the n – 1 disks from Auxiliary tower to Destination tower.
  4. Transferring the top n – 1 disks from Source to Auxiliary tower can again be thought of as a fresh problem and can be solved in the same manner. Once we solve Towers of Hanoi with three disks, we can solve it with any number of disks with the above algorithm.

Recursion And Back Tracking

Problem-2: Given an array, check whether the array is in sorted order with recursion.
Solution:
Recursion And Back Tracking

Time Complexity: O(n). Space Complexity: O(n) for recursive stack space.

What is Backtracking?
Backtracking is an improvement of the brute force approach. It systematically searches for a solution to a problem among all available options. In backtracking, we start with one possible option out of many available options and try to solve the problem if we are able to solve the problem with the selected move then we will print the solution else we will backtrack and select some other option and try to solve it. If none of the options work out we will claim that there is no solution for the problem.

Backtracking is a form of recursion. The usual scenario is that you are faced with a number of options, and you must choose one of these. After you make your choice you will get a new set of options; just what set of options you get depends on what choice you made. This procedure is repeated over and over until you reach a final state. If you made a good sequence of choices, your final state is a goal state; if you didn’t, it isn’t.

Backtracking can be thought of as a selective tree/graph traversal method. The tree is a way of representing some initial starting position (the root node) and a final goal state (one of the leaves). Backtracking allows us to deal with situations in which a raw brute-force approach would explode into an impossible number of options to consider. Backtracking is a sort of refined brute force. At each node, we eliminate choices that are obviously not possible and proceed to recursively check only those that have potential.

What’s interesting about backtracking is that we back up only as far as needed to reach a previous decision point with an as-yet-unexplored alternative. In general, that will be at the most recent decision point. Eventually, more and more of these decision points will have been fully explored, and we will have to backtrack further and further. If we backtrack all the way to our initial state and have explored all alternatives from there, we can conclude the particular problem is unsolvable. In such a case, we will have done all the work of the exhaustive recursion and known that there is no viable solution possible.
  1. Sometimes the best algorithm for a problem is to try all possibilities.
  2. This is always slow, but there are standard tools that can be used to help.
Tools: algorithms for generating basic objects, such as binary strings [2n possibilities for n-bit string], permutations [n!], combinations [n!/r!(n – r)!], general strings [k –ary strings of length n has kn possibilities], etc…

Backtracking speeds the exhaustive search by pruning.

Example Algorithms of Backtracking
  1. Binary Strings: generating all binary strings
  2. Generating k – ary Strings
  3. N-Queens Problem
  4. The Knapsack Problem
  5. Generalized Strings
  6. Hamiltonian Cycles [refer to Graphs chapter]
  7. Graph Coloring Problem
Backtracking: Problems & Solutions
Problem-3 Generate all the strings of n bits. Assume A[0..n – 1] is an array of size n.
Solution:
Recursion And Back Tracking

Let T(n) be the running time of binary(n). Assume function printf takes time O(1).
Recursion And Back Tracking

Using Subtraction and Conquer Master theorem we get T(n) = O(2n). This means the algorithm for generating bit-strings is optimal.

Problem-4 Generate all the strings of length n drawn from 0… k – 1.
Solution: Let us assume we keep the current k-ary string in an array A[0.. n – 1]. Call function kstring(n, k):
Recursion And Back Tracking

Let T(n) be the running time of k – string(n). Then,
Recursion And Back Tracking

Using Subtraction and Conquer Master theorem we get T(n) = O(kn).

Note: For more problems, refer to the String Algorithms chapter.

Problem-5 Finding the length of connected cells of 1s (regions) in a matrix of Os and 1s: Given a matrix, each of which maybe 1 or 0. The filled cells are connected form a region. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally. There may be several regions in the matrix. How do you find the largest region (in terms of the number of cells) in the matrix?
Recursion And Back Tracking

Solution: The simplest idea is: for each location traverse in all 8 directions and in each of those directions keep track of maximum region found.
Recursion And Back Tracking


Recursion And Back Tracking


Recursion And Back Tracking


Recursion And Back Tracking

Problem-6 Solve the recurrence T(n) = 2T(n – 1) + 2n.
Solution: At each level of the recurrence tree, the number of problems is double from the previous level, while the amount of work being done in each problem is half from the previous level. Formally, the ith level has 2i problems, each requiring 2n–i work. Thus the ith level requires exactly 2n work. The depth of this tree is n, because at the ith level, the originating call will be T(n – i). Thus the total complexity for T(n) is T(n2n).

Here, in this article, I try to explain Recursion And BackTracking. I hope you enjoy this Recursion And BackTracking article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Summary:
I hope this post will be helpful to understand the concept of Recursion And Back Tracking
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • Usability of SecureString object in C#
    Introduction Hi friends! In this blog we will be discussing a very interesting as well as useful topic in C# and that is Securestring objec...
  • ASP.NET State Management
    State management is a technique or way to maintain / store the state of an Asp.Net controls, web page information, object/data, and user in ...
  • Application Life cycle of Asp.Net MVC
    Today i am going to tell you the Application life cycle of an Asp.Net MVC Application, this post is important for those who are new to Asp.N...
  • C# Programming Interview Questions
    Today i am going to tell you some of the basic programming questions that are frequently asked in interview for fresher and experienced as w...
  • OOPS – Difference Between Class and Struct
    Hi friends! Today we are going to discuss a very quite interesting and important topic of Object Oriented Programming(OOPs) i.e. “Classes an...
  • Navigation Menus in ASP.NET Core
    In this article, I am going to discuss how to create Responsive Navigation Menus in ASP.NET Core Application using bootstrap and JQuery. P...
  • ViewImports in ASP.NET Core MVC
    In this article, I am going to discuss the ViewImports in ASP.NET Core MVC Application. Please read our previous article before proceeding...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape