Entity Framework First Example - Microsoft Entity Framework

What is Entity framework First Example?

Let’s describe a very simple model using lessons. We’re just defining them in the Program’s file but in a real-world application you will open your classes into separate files and potentially a separate project. Following is a data model which we will be create using Code First approach.
model_using_classes

Create Model

Add the following three lessons in Program’s file using the following code for Student class.

  • The ID property will become the primary key column of the database table that corresponds to this class.
  • The Enrolments property is a navigation property. Navigation properties hold other entities that are related to this entity.
  • In this case, the Enrolments property of a Student entity will hold all of the Enrolment entities that are related to that Student entity.
  • Navigation properties are typically defined as virtual so that they can take advantage of certain Entity Framework functionality such as lazy loading.
  • If a navigation property can hold multiple entities (as in many-to-many or one-to many relationships), its type must be a list in which entries can be added, deleted, and updated, such as I Collection.

Following is the execution for Course class.

The Enrolments property is a navigation property. A Course entity can be linked to any number of Enrolment entities.

Following is the operation for Enrolment class and enema.

  • The Enrolment property will be the primary key.
  • The Grade property is an enemy. The question mark after the Grade type declaration indicates that the Grade property is null able.
  • A grade that's null is different from a zero grade. Null means a grade isn't known or hasn't been assigned yet.
  • The Student and Coursed properties are foreign keys, and the corresponding navigation properties are Student and Course.
  • An Enrolment entity is associated with one Student and one Course entity, so the property can only hold a single Student and Course entity.

Create Database Context

The main class that coordinate Entity Framework functionality for a given data model is the database context class which allows to query and save data. You can create this class by derive from the DbContext class and exposing a typed Best for each class in our model. Following is the performance on My Context class, which is derived from DbContext class.

Following is the complete code in Program’s file.


The above code is all we need to start storing and retrieve data. Let’s add some data and then retrieve it. Following is the code in main method.

When the above code is executed, you will obtain the following output.


Now the question that comes to mind is where are the data and the database in which we have added some data and then retrieve it from database. By standard, DbContext has formed a database for you.

  • If a local SQL Express instance is available then Code First has created the database on that instance.
  • If SQL Express isn’t available, then Code First will try and use Local.
  • The database is named after the fully qualified name of the derived context.

In our case, SQL Express instance is presented, and the database name is EFCodeFirstDemo.MyContext as exposed in the following image.


sql_express_instance

  • These are just the default conventions and there are various ways to change the database that Code First uses.
  • As you can see in the above image, it has created Students, Courses and Enrolments tables and each table contains columns with appropriate data type and length.
  • The column names and data type also match with the properties of the respective domain classes.

Database Initialization

In the above instance, we have seen that Code First creates a database automatically, but if you want to change the name of the database and server, let us see how Code First decide the database name and server while initializing a database. Take a look at the following figure.
database_initialization

You can describe the base constructor of the context class in the following way.

  • No Parameter
  • Database Name
  • Connection String Name

No Parameter

If you identify the base constructor of the context class without any parameter as exposed in the above instance, then entity framework will create a database in your local SQLEXPRESS server with a name {Namespace}.{Context class name}.

In the above illustration, the database which is created automatically has the name EFCodeFirstDemo.MyContext. If you look at the name, you will find that EFCodeFirstDemo is the namespace and My Context is the context class name as exposed in the follow code.

Database Name

If you pass the database name as a parameter in a base constructor of the context class, then Code First will create a database manually again, but this time the name will be the one passed as parameter in the base constructor on the local SQLEXPRESS database server.
In the following code, MyContextDB is specific as parameter in the base constructor. If run your application, then the database with MyContextDB name will be created in your local SQL server.

Connection String Name

This is an simple way to tell DbContext to use a database server other than SQL Express or Local. You may choose to put a connection string in your app.config file.

  • If the name of the connection string matches the name of your context (either with or without namespace qualification), then it will be found by DbContext when the parameter less constructor is used.
  • If the connection string name is different from the name of your context, then you can tell DbContext to use this connection in Code First mode by passing the connection string name to the DbContext constructor.

  • In the above code, snippet of context class connection string is specified as a parameter in the base constructor.
  • Connection string name must start with "name=" otherwise, it will consider it as a database name.
  • This form makes it explicit that you expect the connection string to be found in your comfit file. An exception will be thrown if a connection string with the given name is not found.

  • The database name in the association string in app.config is EFMyContextDB. Code first will create a new EFMyContextDB database or use existing EFMyContextDB database at local SQL Server.

Domain Classes

So far we’ve just let EF determine the model using its defaulting convention, but there are going to be times when our classes don’t follow the conventions and we need to be able to perform more configurations. But you can override these conventions by configuring your domain classes to give EF with the information it needs. There are two options to configure your domain classes −

  • Data Annotations
  • Fluent API

Data Annotations

Data Annotations is used to configure your classes which will highlight the most normally needed configurations. Data Annotations are also understand by a number of .NET applications, such as ASP.NET MVC which permit these applications to control the same explanation for client-side validations.

Following are the data explanation used in student class.

Fluent API

Most model configuration can be done using simple data explanation. The fluent API is a basic way of specifying model configuration that covers everything that data explanation can do, in addition to some more advanced configuration not possible with data explanation. Data explanation and the fluent API can be used mutually.

To access the fluent API you override the OnModelCreating method in DbContext. Now let’s rename the column name in student table from FirstMidName to First Name as publicized in the following code.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Microsoft Entity Framework Topics