• 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
Showing posts with label Entity Framework. Show all posts
Showing posts with label Entity Framework. Show all posts

Sunday, August 23, 2020

DbContext in Entity Framework Core

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

In this article, I am going to discuss DbContext in Entity Framework Core in detail. Please read our previous article where we discussed how to install entity framework core in visual studio step by step. DbContext class is one of the important classes in entity framework core and at the end of this article, you will understand the significance of the DbContext class in Entity Framework Core. As part of this, we will discuss the following pointers.
  1. What is a DbContext class?
  2. How to create and use the DbContext class?
  3. DbContextOptions class in Entity Framework Core
  4. Entity Framework Core DbSet
What is a DbContext class?
The DBContext class is basically used by our application to interact with the underlying database. That means this class is used to manage the database connection as well as also used to perform CRUD operation with the underlying database.

How to create and use the DbContext class in Entity Framework Core?
In order to use the DbContext class in your application, you need to create a class derives from the DbContext class. The DbContext class present is in Microsoft.EntityFrameworkCore namespace.

So, within the models’ folder create a class file with the name StudentDbContext and then inherit from the class from DbContext class as shown in the below image. You can provide any name for your DbContext class, as I am going to develop an application to manage the students, so I gave the name as StudentDbContext.
How to create and use the DbContext class in Entity Framework Core

DbContextOptions class in Entity Framework Core:
In order to perform any useful task by the DbContext class, we need an instance of the DbContextOptions class. The instance of the DbContextOptions carries all the required configuration information such as the connection string, database provider, etc.

To pass the DbContextOptions instance we need to use the constructor of StudentDbContext class as shown in the image below.
DbContextOptions class in Entity Framework Core

In our next article, we will discuss the DbContextOptions class in detail.

Entity Framework Core DbSet:
The entity framework code DbContext class includes a property i.e. DbSet for each entity in your application. Let us understand this with an example. Create three entities such as Student, Branch, and Address within the Models folder as shown below.
namespace FirstCoreMVCApplication.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public int BranchId { get; set; }
    }
    public class Branch
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    public class Address
    {
        public int Id { get; set; }
        public int StudentId { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
        public string Pin { get; set; }
    }
}
As our application contains three entities, so in our StudentDbContext class, we need to have three DbSet Properties as shown below.
Entity Framework Core DbSet

We will use the above DbSet properties such as Students, Branches, and Addresses to perform CRUD Operations.

So, the complete code of the StudentDbContext class is given below.
using Microsoft.EntityFrameworkCore;
namespace FirstCoreMVCApplication.Models
{
    public class StudentDbContext : DbContext
    {
        public StudentDbContext(DbContextOptions<studentdbcontext> options)
               : base(options)
        {
        }
        public DbSet<student> Students { get; set; }
        public DbSet<branch> Branches { get; set; }
        public DbSet<address> Addresses { get; set; }
    }
}
So, in Short,
The DbContext in Entity Framework Core perform the following tasks:
  1. Manage database connection
  2. Configure model & relationship
  3. Querying database
  4. Saving data to the database
  5. Configure change tracking
  6. Caching
  7. Transaction management
In order to connect to a database, we need the database connection string. So, in the next article, I am going to discuss, where to define the connection string and how to use it in Entity Framework Core to interact with the SQL Server Database. Here, in this article, I try to explain the need and use of the DbContext class in Entity Framework. I hope you enjoy this article.

Summary:
I hope this post will be helpful to understand the concept of DbContext in Entity Framework Core
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

Saturday, August 22, 2020

How to Install Entity Framework Core

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

In this article, I am going to discuss How to Install Entity Framework Core in Visual Studio step by step in different types of applications. Please read our previous article where we discussed the introduction part of Entity Framework Core.

Note: The Entity Framework Core can be used with .NET Core applications as well as .NET 4.6 based applications. Here, in this article, I will show you how to install EF Core in .NET Core applications using Visual Studio 2017.

The Entity Framework Core is not a part of .NET Core and standard .NET framework. It is available as a NuGet package. Depending on how you have set your project, you may have already installed the Entity Framework Core.

Depending on the project complexity or requirement, you can develop a web application as:
  1. Single Layer Web Application
  2. Multi-Layer Web Application
Single Layer Web Application
When you develop a small project, then you may have the presentation, business, and data access layer all in one project. So when we created a web application project using ASP.NET Core 2.1 or higher, then by default the Entity Framework Core already installed.

Entity Framework Core in ASP.NET Core Web Application Project
When we create an ASP.NET Core Web application using ASP.NET Core 2.1 or higher version, then by default the following NuGet package installed.

Microsoft.AspNetCore.App

The above package is called a Meta package. A Meta package does not hold any content of its own rather it holds a list of other packages. You can find this Meta package, in the Solution Explorer under the NuGet section. When you expand the Meta package, then you can find all the dependencies i.e. other packages. In the dependencies, once you scrolled down then you will find the Entity Framework Core NuGet packages already installed as shown in the below image.
Entity Framework Core Nuget Packages in ASP.NET Core Web Application

So the point that you need to remember is, when you create an ASP.Net Core web application using ASP.NET Core Version 2.1 or later, then by default you will have Entity Framework Core installed as part of the meta-package.

Multi-Layer Web Application:
When we want to develop a large application, we usually have at least the following 3 layers
  1. Presentation Layer
  2. Business Logic Layer
  3. Data Access Layer
These layers are implemented as separate projects. And the Entity Framework Core is usually required in the Data Access Layer project as this layer is going to interact with the database. The Data Access Layer project is usually a class library project and a class library project by default does not usually have the meta-package referenced. As it does not have the meta-package installed, so this means, the Entity Framework Core is not installed for the Data Access Layer project.

In order to install the Entity Framework Core to interact with the SQL server database, you need to install the following NuGet packages.
How to Install Entity Framework Core in Visual Studio

  1. Microsoft.EntityFrameworkCore.SqlServer has a dependency on Microsoft.EntityFrameworkCore.Relational package.
  2. Similarly, Microsoft.EntityFrameworkCore.Relational package has a dependency on Microsoft.EntityFrameworkCore package.
  3. Microsoft.EntityFrameworkCore package has a dependency on several other packages.

Entity Framework Core Packages Dependency

Note: When you install Microsoft.EntityFrameworkCore.SqlServer package, then it also automatically installs all the other dependency NuGet packages.

Installing Entity Framework Core in the Class Library Project:
Create a class library Project. Once you create the class library project expand the dependencies node as shown below.
Installing Entity Framework Core in the Class Library Project

As you can see in the above image, we don’t have the meta-package installed and hence we don’t have the entity framework core installed in our application.

In order to install entity framework core, Right-click on the “Dependencies“ node in Solution Explorer and then select “Manage NuGet Packages“ from the context menu as shown in the below image.
Installing Entity Framework Core

This will open the NuGet Package Manager interface. Click on the Browse tab and search for Microsoft.EntityFrameworkCore.SqlServer in the search box at the top left corner as shown in the below image. Based on the asp.net core version installed the entity framework core version compatibility with your .net core framework.
Installed Entity Framework Core

Note: We want to install Entity Framework Core to interact with the SQL Server database, so we installed the Microsoft.EntityFrameworkCore.SqlServer package. This package is usually called the Database provider package.

If you are using a different database other than SQL server, then you need to install that database provider-specific NuGet package. For example, if you want to use MySQL as your database, then install Pomelo.EntityFrameworkCore.MySql database provider package. Along the same lines, if you want to use PostgreSQL as your database, then use Npgsql.EntityFrameworkCore.PostgreSQL database provider package.

You can find all provider-specific NuGet packages on the following MSDN page.

https://docs.microsoft.com/en-us/ef/core/providers/

When you are installing the entity framework it will ask you to accept the license terms associated with the packages that are going to be installed as shown in the image below. Accept the license.
Accepting Terms in Entity Framework Core

Once the entity framework core installed, you will find the packages in the Meta package as shown in the below image.
Entity Framework Core Meta packages

Alternatively, you can also use the Package Manager Console to install the Entity Framework Core package. Go to Tools -> NuGet Package Manager -> Package Manager Console and execute the following command to install the SQL Server provider package.

PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer

In the next article, I am going to discuss the DbContext class in Entity Framework Core. Here, in this article, I try to explain how to install the entity framework core.

Summary:
I hope this post will be helpful to understand How to Install Entity Framework Core
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 Core

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

In this article, I am going to give you an overview of Entity Framework Core. The Entity Framework Core which is also known as EF Core is the latest version of Entity Framework and completely rewrites from the ground up. As part of this article, we are going to discuss the following pointers.
  1. What is Entity Framework Core?
  2. What is ORM?
  3. Why do we need to use an ORM?
  4. EF Core Development Approaches.
  5. EF Core Code First Approach
  6. Entity Framework Core Database-First Approach
  7. EF Core Database Providers
  8. Why need to use Entity Framework Core over EF 6.x?
What is Entity Framework Core?
Entity Framework (EF) Core is an ORM (Object-Relational Mapper) Framework for data access in .Net. It was released along with .NET Core and is an extensible, lightweight, Open Source, and cross-platform version of Entity Framework data access technology. It works on multiple operating systems like Windows, Mac, and Linus.

What is ORM?
The term ORM stands for Object-Relational Mapper and it automatically creates classes based on database tables and the vice versa is also true. That is, it can also generate the necessary SQL to create the database based on the classes.

As a developer, we mostly work with the application business objects and the ORM Framework generates the necessary SQL (to perform the CRUD operation) that the underlying database can understand. So, in simple words, we can say that the ORM Framework eliminates the need for most of the data access code that as a developer we generally write.

Why do we need to use an ORM?
Let us understand why we need to use the ORM Framework with an example.

Suppose we want to develop an application to manage the students of a college. In order to do this, we may need to create classes such as Student, Department, Address, etc. Technically we called these classes as Domain classes.

Without using ORM Framework like Entity Framework or EF Core, we have to write lots of data access code to perform the CRUD operations i.e. store and retrieve the Student, Department and Address data from the underlying database tables.

For example, in order to perform CRUD operations i.e. read, insert, update or delete from a database table, we generally need to write custom code in our application to generate the required SQL statements which can be understood by the underlying database. Again, when we want to read the data from the database into our application, then also we have to write some custom code to map the database data to our model classes like Student, Department, Address, etc. This is a very common task as a developer for us that we do almost in every application.

An ORM Framework like Entity framework or EF Core can do all of the above for us and saves a lot of time if we provide the necessary required information to the ORM Framework. The ORM Framework sits between our application code and the Database. It eliminates the need for most of the custom data-access code that we usually write without an ORM.
Why do we need to use an ORM

EF Core Development Approaches:
Entity Framework Core supports two development approaches. They are as follows:
  1. Code-First Approach
  2. Database-First Approach
EF Core mainly targets the code-first approach and provides little support for the database-first approach at the moment.

EF Core Code First Approach:
In the EF Core Code First Approach, first, we need to create our application domain classes such as Student, Branch, Address, etc. and a special class that derives from Entity Framework DbContext class. Then based on the application domain classes and DBContext class, the EF Core creates the database and related tables.
Entity Framework Core Code First Approach

Out of the box, in the code-first approach, the EF Core API creates the database and tables using migration based on the default conventions and configuration. If you want then you can also change the default conventions used to create the database and its related tables. This approach is useful in Domain-Driven Design (DDD).

EF Core Database First Approach:
If you have an existing database and database tables are already there, then you need to use the EF Core Database First Approach. In the database-first approach, the EF Core creates the DBContext and Domain classes based on the existing database schema using EF Core Command.
Entity Framework Core Database First Approach

EF Core Database Providers:
The EF Core supports both relational and non-relational databases and this is possible due to database providers. The database providers are available as NuGet packages. The Database Provider sits between the EF Core and the database it supports.
Entity Framework Core Database Provider

The EF Core database provider usually contains the functionality specific to the database it supports.
  1. Functionality that is common to all the databases is in the EF Core component.
  2. Functionality that is specific to a database, for example, Microsoft SQL Server-specific functionality is with-in the SQL Server provider for EF Core.
The following image shows the database providers and the NuGet packages for EF Core.
NuGet Package References For Database Providers

For the complete list of EF Core Database Providers, please visit the following URL.

https://docs.microsoft.com/en-us/ef/core/providers/

We will discuss Database providers in detail in our upcoming articles.

Why need to use Entity Framework Core over EF 6.x?
The EF 6.x is a stable and fully tested ORM technology and used in many applications. EF Core also provides an experience similar to EF 6.x. However, it is built upon a new set of components. The application targets to .NET Core e.g. ASP.NET Core applications. Universal Windows Platform (UWP) Applications cannot use EF 6.x as this requires the complete .NET Framework. EF Core is more suitable for such applications. Although both of these releases provide similar features, EF Core does not have the following features:
  1. Spatial Type
  2. Complex/value types
  3. EDMX Model format
  4. Lazy loading
  5. Stored Procedures
The complete list of features not available in EF Core and a side-by-side comparison with EF 6.x can be found at Feature Comparison. The EF Core does not support all the features provided by Entity Framework 6.x. However, following are some reasons to use EF Core:
  1. Simple to get started
  2. It supports NoSQL Databases along with relational databases
  3. It fits nicely in ASP.NET MVC Core setup
  4. Integrates well with LINQ
  5. Possible to use on Linux and Mac since it is based on .NET Core along with Windows.
In the next article, I am going to discuss how to install the entity framework core in visual studio. Here, in this article, I gave a brief introduction to Entity Framework Core.

Summary:
I hope this post will be helpful to understand the Introduction of Entity Framework Core
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

Friday, August 7, 2020

Development Approach with Entity Framework

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

In this article, I will discuss Development Approach with Entity Framework. The entity framework provides three different approaches when working with the database and data access layer in your application as per your project requirement. These are
  1. Database-First
  2. Code-First
  3. Model-First
Database-First Approach:
We can use the Database First approach if the database schema already existing.

In this approach, we generate the context and entities for the existing database using the EDM wizard.

This approach is best suited for applications that use an already existing database.
Development Approach with Entity Framework

Database First approach is useful:
  1. When we are working with a legacy database
  2. If we are working in a scenario where the database design is being done by another team and the application development starts only when the database is ready
  3. When we are working on a data-centric application
Code-First Approach:
You can use the Code First approach when you do not have an existing database for your application. In the code-first approach, you start writing your entities (domain classes) and context class first and then create the database from these classes using migration commands.

This approach is best suited for applications that are highly domain-centric and will have the domain model classes created first. The database here is needed only as a persistence mechanism for these domain models.

That means Developers who follow the Domain-Driven Design (DDD) principles, prefer to begin coding with their domain classes first and then generate the database required to persist their data.
Development Approach with Entity Framework

Code First approach is useful:
  1. If there is no logic is in the database
  2. When full control over the code, that is, there is no auto-generated model and context code
  3. If the database will not be changed manually
Model-First Approach:
This approach is very much similar to the Code First approach, but in this case, we use a visual EDM designer to design our models. So in this approach, we create the entities, relationships, and inheritance hierarchies directly on the visual designer and then generate entities, the context class, and the database script from your visual model.

Note: The visual model will give us the SQL statements needed to create the database, and we can use it to create our database and connect it up with our application.
Development Approach with Entity Framework

The Model First approach is useful:
  1. When we really want to use the Visual Entity Designer
Choosing the Development Approach for Your Application:
The below flowchart explaining which is the right approach to develop your application using Entity Framework?
Development Approach with Entity Framework

As per the above diagram, if you have an existing database, then you can go with Database First approach because you can create an EDM from your existing database.

But if you don’t have an existing database but you have an existing application with domain classes then you can go with code first approach because you can create a database from your existing classes.

But if you don’t have either existing database or domain model classes then you can go with the model first approach.

In the next article, I will discuss the DB First approach of Entity Framework.

In this article, I try to explain the Development Approach with 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 Development Approach with 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 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
Older Posts

Join us on Telegram

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

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

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