Entity Framework- A Complete Encyclopedia - NareshIT
Entity Framework- A Complete Encyclopedia

Entity Framework- A Complete Encyclopedia - NareshIT

EF Core: The Complete Encyclopedia

Various Prerequisites for the Entity Framework are as below:

  • C#
  • VS 2019
  • MS SQL Server and Queries

What happens to be the Entity Framework Core?

The MS Entity Framework Core happens to be the Microsoft’s implementation of the ORM framework. The application that we develop with the help of Entity Framework does not work directly with the database. The application works with the API only which is leveraged by the EF for all database related operations. The Entity framework maps the operations to the database. Naresh I Technologies is the number one computer training institute in Hyderabad, and it is among the top five computer training institutes in India. Contact us anytime for your complete dot net training.

Applying entity framework core for making console operations

Here you will learn how to make Entity framework core console application. We will show you how to create console application as well as install all required dependencies. And then we will make entity model and create a DBcontext which is used for managing the entity model for creation of DBset properties. Then we will learn how to use migration features of the EF core for creating a database. Then we will see how we can use of CRUD operations on the models and persist the data into database.

Installing Visual Studio 2019


It's a straightforward installation process and you need to download the Visual Studio 2019 community edition since you are in learning phase, and this is free.


Creating control application with the help of Entity Framework Code

  • The first step is creation of Entity Framework or Console Application.
  • Go to VS 2019 and click on option create new project. Then from file>new>project for starting new project.
  • Now you are required to select the console and then pick the template console.net core. Now as you are done tap over the next.?
  • Now you need to enter the name of the project and click create for creating new console project.

Installation of Entity Framework Core

Now the next step is the installation of the Entity Framework Core.

The “Microsoft.EntityFramework.Core” is the core library. However installation alone is not enough. You are also mandatory to mount the EF core database provider. There are numerous database providers which are obtainable with EF core and you will find broad list of database provider.

As an example, for making use of SQL Server you need to install Microsoft.EntityFramework. Core. SQLServer. For SQLITE you need to install Microsoft.EntityFramework.Core.SQLITE. For this article we need to use SQL Server and hence we will install the package accordingly as explained above.


We are going to make use of Nuget Package Manager for installing the Entity Framework Core.

You need to follow certain steps as below:

  • Tap on tools and then Nuget Package Manager and then manage nuget package for solution. Now click on Browse. Type in Microsoft.EntityFrameworkCore,SqlServer and then hit search. Now select Microsoft.EntityFrameworkCore.SqlServer and then choose EFCore.
  • Now clack on install.
  • Then tap on I accept as being requested.
  • The bundle then will “install” and you are ready.

Various Entity Framework Core Tool Jnstallations:

The entity framework core comes with Command Line Interface or CLI tools.? And these tools cover the commands for creating migration and applying migrations as well as produce script migrations and produce code for the model based on the database which is existing.

Now open the manage nuget package for solution window and hunt for Microsoft.EntityFramework.Core. tools and finally install it.

Database Modeling

The EF core completes the data access with the help of model. The model happens to be POCO class. In Entity Framework Core it is known as Entity Class.

The EF core atlases the entity class to the table of the db.

Here and now we need to create Sample Entity Class.

Now right clunk on the solution folder and then generate the folder “models.”

  1. Now underneath the model’s folder you prerequisite to right click and then formulate a class Sample. Now transform the class to the public and add two properties uid and sampleName as depicted below in code:

namespace EFCore.Models

{

????public class Sample

????{

????????public int uid { get; set; }

????????public sampleName { get; set; }

????}

The DBCotext class

Db Class manages that entity class or the models. This happens to be the main part of the entity framework core. It is accountable for database connection, querying and updating of database. It also stores the information required for database configuration etc. Naresh I Technologies is the number one computer training institute in Hyderabad, and it is among the top five computer training institutes in India. Contact us anytime for your complete dot net training.

We need to create our context class by accede to the DBContext. Now beneath the model folder you prerequisite to create EFContext class and now copy paste the below code.

?

namespace EFCore.Models

{

????public class EContext : DbContext

????{

?

????????private const string conString = “ write connection string here.”

?

????????protected override void OnConfiguring(DbContextOptionsBuilder optBuilder)

????????{

????????????optBuilder.UseSqlServer(conString);

????????}

?

????????public DbSet<Samplet> Samples { get; set; }

?

????}

}

Now we need to comprehend whole code.?

The EContext class accede to the DBContext as publicized below:


public class EContext : DbContext

Subsequent, we will frame the connection string.

private const string conString = "Server=(localdb)\\mssqllocaldb;Database=EF;Trusted_Connection=True;";

?

The onconfiguring method benefit us in conformation of DBContext. The EF core labels this method as it instantiate the context initially. And this is where the configuration of Context class is done. As an instance, we organize the database provider under connection string to be cast-off etc.

With the assistance of onconfiguring method we can get the instance of DBContextOptionsBuiler in the formulation of argument. The DBContextOptionsBuilder leverage us with API for conformation of DBContext.?


protected override void OnConfiguring(DbContextOptionsBuilder optBuilder)


?????


Within the onconfiguring method, we can call UseSQLServer extension method which is provided by Microsoft.EntityFrameworkCore.SQLServer.


The UseSqlServer method configure the SQLSERVER as our database provider. The first argument for this is the connection string.


optionsBuilder.UseSqlServer(conString);


Here the connection string is hardcoded. Though, you can brand use of configuration system which is providing by dot net core for storage of con string in external file.

DbSet

Creation of model or entity type is not enough for mapping it to database. We need to create DBSet property for all models which are in the Context Class. The EF core covers all those types which are having DbSet property in the model.?

The DbSet leverage us with methods like remove, attach, add etc over the entity type. The Context class does the mapping of these operations with the SQL query and then runs it WRT database with the help of Database Providers. Naresh I Technologies is the number one computer training institute in Hyderabad, and it is among the top five computer training institutes in India. Contact us anytime for your complete dot net training.


DbSet<Sample> Samples { get; set; }

Creation of the Db

Here and now we are prepared with our models. Our model comes with a entity type called Sample. And we have made EContext class for model management. We have also?

formulated the Dbset property of the sample so that it gets covered in the model. Now we need to make a db.

In EF core we apply migrations for making of the db.

Addition of migrations

Click on the tools and then select npm followed by the package manager console for going to the console.

Now you are required to execute “add migration” command.

add-Migration “Database1”

The add migration produces the instruction for creating SQL command for updating the db for matching the model. You can see that numerous files are shaped is added underneath the migrations folder.

Creation of Database

The following step is for generating the db with the assistance of migrations that we finished in the preceding step.

You need to unclutter the package manager console and then route the command “update database”. This command makes usage of migrations for producing SQL queries for updating the db. If the db does not exist it will make it. I need to brand use of con string provided during the conformation of DBContext for linking to the database.

Scrutiny whether db has been formed:

You need to clack on view and then ask where server object explorer for opening SQL Server object explorer. Move to (localDB)\mssqldb. Now you will get the EF dB has been produced.

CRUD Operations

The crud process add, create, update, read, and delete processes on the sample entity model and then it persist to the database the facts.

Inserting Data

Insert and to the database can be handled with the assistance of SaveChanges method of the DBContext object.

For doing that you prerequisite to track below stages;

You prerequisite to make a new case of DBContext class.

using (var db = new EFContext())

?

Now you prerequisite to generate the new instance of domain class template and allocate values to all its chattels.

Sample sample = new Sample();

sample..samplename = "Basket";

Now you prerequisite to augment it to the DBContext class such that the context originates to recognize about the entity.

db.Add(sample);

Lastly, we prerequisite to call the SaveChanges method of the DBContext for persevering the changes to the db.

Underneath is a incline of comprehensive insertSample method, that is appealed from the main method of the program.cs.?

using EFCore.Models;

using System;

?

namespace EFCore

{

????class Program

????{

????????static void Main(string[] args)

????????{

????????????insertSample();

?

????????????Console.WriteLine(“Press for coninuing");

????????????Console.ReadKey();

????????}

?

????????static void insertSample()

????????{

????????????using (var d = new EContext())

????????????{

????????????????Sample sample = new Sample();

????????????????sample.sampleName= "Basket";

????????????????d.Add(sample);

?

???????????????sample= new Sample();

????????????????sample.sampleName = "Cup";

????????????????d.Add(sample);

?

????????????????d.SaveChanges();

????????????}

????????????return;

????????}

?

????}

}

Now route the code and go to the db for confirming that the values are inserted or not. you will discover the values nserted.


Interrogating Data


The queries are inscribed in contradiction of the DBSet property of the entity. They need to be written with LINQ to entities API. We have two strategies for writing queries with LINQ. The first is the method syntax and the second is a syntax in the form of query.?

The below program code recovers the sample with the aid of method syntax. It make use of ToList() method of theDBSet(). This directs the select query to the db and regain the outcome and translate it to the list of samples.

using System.Linq;

?

static void readSample()

{

?

????using (var d = new EContext())

????{

????????List<Sample> samples = d.Samples.ToList();

????????foreach (Sample s in samples)

????????{

????????????Console.WriteLine(s.uid, s.sampleName);

????????}

????}

????return;

}

And in the main you need calling the readSample.

?

static void Main(string[] args)

{

????

?

????readSample();

????Console.ReadKey();

?

}


Update Record

The below code stores how we can keep posted a sole entity. At first we need to use find method for retrieving single sample. The find method takes in the pk of the Sample as the argument and salvages the Sample from the db and then it does a charting of it into the Sample entity. Subsequent, we update the Sample entity. In conclusion, we style use of SaveChanges method for keep posted the database.

static void updateSample()

{

????using (var d = new EContext())

????{

????????Sample sample = d.Samples.Find(1);

????????sample.Name = "Better basket";

????????d.SaveChanges();

????}

????return;

}

? In the main method we prerequisite to appeal the update sample and read sample for confirming whether the value have been changed or not.

static void Main(string[] args)

{

????

????readSample();

????updateSample();

????readSample();

?

????Console.ReadKey();

}



Delete Record

The subsequent code explains how we can delete the record from the db. Erasing can be done with the assistance of remove method of the DBSet. We need to provide entity argument for the remove method which is coded below:

static void deleteSample()

{

????using (var d = new EContext())

????{

?

????????Sample sample = d.Samples.Find(1);

????????d.Samples.Remove(sample);

????????d.SaveChanges();

????}

????return;

}



And now in the main method we need to call the read sample for confirming whether the values have been transformed or not.


static void Main(string[] args)

{

????

????readSample();

????deleteSample();

????readSample();

?

????

????Console.ReadKey();

}


Summary

That's above we cultured how to generate a console object with the help of entity core framework and we also created a model. Then we added DBContext to the venture and pass the con string to it. then we included the DBSet property for the sample model to the context class. the contacts does the management of all models and it disclosures the DBSet assets, then we made use of the migrations for creating a database and we also saw how to do the crude operations on the database with the help of entity framework core. However, the story does not end here, and we can do a world of good with the entity framework and the database. We can have numerous entities and then create relationship between them after creating various keys like primary keys and the foreign keys. And there are lot of things that can be done with the help of the entity framework. And that is why we say that entity framework is the connection in between the database and the entity classes, that is created with the help of Context? class that inherits the DBContext.? And we have discussed all that in this article, however, there is a lot of things that you can do, and you can a world of good.? And that we are going to see in the next blog on Entity Framework.??

Naresh I Technologies is the number one computer training institute in Hyderabad, and it is among the top five computer training institutes in India. We provide complete dot net training .?

We provide counselor service as well. Just give us a missed call, and one of our counselors will be calling you and briefing all the courses that we provide. You can choose one as per your choice.?

And what you will get through dot net training:

  • You have the freedom to choose from the dot net training and dot net online training .?
  • You will get the training from one of the best dot net training institutes, and one of the best faculty in India.
  • We provide dot net training in Hyderabad and the USA. However, you can contact us for the dot net training from any part of the world.?
  • Naresh I Technologies provides one of the best dot net training in India and has a world-class computer lab. However, you can opt for practicals from your home as well. And we will provide you complete practical training from the comfort of your home.?
  • We provide well research content materials for your future reference.
  • Our faculty trains the professionals as well as the freshers in their unique way, with a precise style of teaching for the professionals as we know they require a lesser number of words?
  • And a lot more is waiting for you.

Contact us anytime for your dot net training, and from any part of the world. Just give us a missed call and our counselors will be contacting you asap.?

FAQ'S

1. How does Entity Framework handle concurrency conflicts?

Entity Framework uses optimistic concurrency by default, which means it compares the original values of an entity with the modified values before saving changes. If there are conflicts, an exception is thrown. You can also use pessimistic concurrency to lock records during updates.

2. What is the purpose of the DbContext.ChangeTracker?

The DbContext.ChangeTracker tracks changes made to entities within a DbContext. It allows you to inspect the state of entities (added, modified, deleted), intercept changes, and customize behavior.

3. How can you customize the mapping between entity properties and database columns?

You can customize mapping using data annotations or fluent API. For example, you can specify column names, data types, default values, and constraints.

4. What are some common challenges and best practices for using Entity Framework?

  • Performance: Avoid unnecessary queries, optimize query execution, and consider database tuning.
  • Concurrency: Use appropriate concurrency strategies to handle conflicts.
  • Complexity: Understand the underlying concepts and best practices to effectively use Entity Framework.
  • Migrations: Manage schema changes using migrations to avoid manual database updates.
  • Design: Design your entity classes and relationships carefully to maintain a clear and maintainable model.

For More Details Visit : Dot net Online Training

Register For Free Demo on UpComing Batches : https://nareshit.com/new-batches

要查看或添加评论,请登录

Naresh i Technologies的更多文章

社区洞察

其他会员也浏览了