The Entity Framework uses the database through code first

Source: Internet
Author: User
Tags class definition visual studio 2010

Required conditions

You need to install Visual Studio 2010 or Visual Studio 2012, Visual Studio 2013.

If you are using Visual Studio 2010, you will also need to install NuGet.

1. Create an application

For simplicity, we'll build a basic console application that uses Code first to perform data access

    • Open Visual Studio
    • Files, new, projects, ...
    • Choose Windows and console applications from the left menu
    • Enter BlogSolution as Name
    • Select "OK"

2. Create a model

We use classes to define a very simple model. Defined in the Program.cs file, but in a real-world application, the class may be divided into separate files, possibly as separate projects

Under the Program class definition in Program.cs, add the following two classes

 Public classBlog { Public intBlogId {Get;Set; }  Public stringName {Get;Set; }  Public VirtualList<post> Posts {Get;Set; } }   Public classPost { Public intPostID {Get;Set; }  Public stringTitle {Get;Set; }  Public stringContent {Get;Set; }  Public intBlogId {Get;Set; }  Public VirtualBlog Blog {Get;Set; } }

As you can see, we will virtualize two navigation properties (Blog.posts and Post.blog). This enables the lazy load feature of the Entity Framework. Lazy loading means that when you try to access the contents of these properties, it is automatically loaded from the database.

3. Create context

You can now define a derived context that represents a session of the database so that we query and save the data. We define a context that derives from System.Data.Entity.DbContext and exposes a typed dbset<tentity> for each class in the model

Now, start using the type from the Entity Framework. Therefore, we need to add the EntityFramework NuGet package.

    • "Project" –> "Manage NuGet packages ..." Note: If you do not have the "Manage NuGet packages ..." option, you should install the latest version of NuGet
    • Select the "Online" tab
    • Select the "EntityFramework" package
    • Click "Install"

At the top of Program.cs, add a using statement for System.Data.Entity

Under the Post class in Program.cs, add the following derivation context.

 Public class Bloggingcontext:dbcontext {     publicgetset;}       Public Get Set ; } }

Here is a complete list of what Program.cs should now contain

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Data.Entity; namespaceCodefirstnewdatabasesample {classProgram {Static voidMain (string[] args) {         }     }       Public classBlog { Public intBlogId {Get;Set; }  Public stringName {Get;Set; }  Public VirtualList<post> Posts {Get;Set; } }       Public classPost { Public intPostID {Get;Set; }  Public stringTitle {Get;Set; }  Public stringContent {Get;Set; }  Public intBlogId {Get;Set; }  Public VirtualBlog Blog {Get;Set; } }       Public classBloggingcontext:dbcontext { PublicDbset<blog> Blogs {Get;Set; }  PublicDbset<post> Posts {Get;Set; } } }

This is all the code we need to start storing and retrieving data. Obviously, there are a lot of things happening backstage. We'll take a look at it later. But first, let's see how it works.

4. Read and write Data

Implement the Main method in Program.cs, as shown below. The code creates a new instance of the context and then uses that instance to insert a new blog. After that, it uses a LINQ query to retrieve all the blogs in the database (sorted alphabetically by title)

classProgram {Static voidMain (string[] args) {         using(vardb =NewBloggingcontext ()) {             //Create and save a new blogConsole.Write ("Enter name creationBlog:"); varName =Console.ReadLine (); varBlog =NewBlog {Name =name}; Db.             Blogs.add (blog); Db.  SaveChanges ();             varquery = fromBinchdb. Blogs byB.nameSelectb; Console.WriteLine ("All Blogs databases:"); foreach(varIteminchquery) {Console.WriteLine (item.             Name); } Console.WriteLine ("enter any key to exit ...");         Console.readkey (); }     } }

You can now run the application and test it.

You can use Server Explorer to connect to this database in Visual Studio

    • View, Server Explorer
    • Right-click Data Connections and select Add Connection ...
    • If you have not yet connected to the database from Server Explorer, you need to select Microsoft SQL Server as the data source
    • Connect to (local) or ., depending on the installation situation

Now you can check the schema that Code first has created

DbContext See what classes the model contains by looking at our defined DbSet properties. It then uses the default set of Code first conventions to determine the name of the table and column, determine the data type, find the primary key, and so on.

5. Handling Model Changes

Now change the model, and when we make changes, we also need to update the database schema. To do this, we use a feature called "Code First Migration" (or "migration", for short).

Migration is an orderly set of steps that describe how to upgrade (and downgrade) the database schema. Each step in these steps, called migration, contains code that describes the changes to apply.

The first step is to enable the Code first migration for Bloggingcontext.

      • Package Manager console, library Package Manager, tools, and libraries
      • To run the enable-migrations command in the Package Manager console
      • A new migrations folder has been added to the project, it contains two files  
        • Configuration.cs -This file contains the settings that "migration" will use to migrate Bloggingcontext. You do not need to make any changes in this walkthrough, but you can specify the seed data here, register the provider for another database, change the namespace for the build migration, and so on.
        • < timestamp >_initialcreate.cs -This is the first migration, which represents a change that has been applied to the database. The purpose of applying the change is to migrate it from an empty database to a database that contains blogs and article tables. Although we let Code first create these tables automatically, we now choose "Migrate" (converted to a "migration"). Code first is also logged in the local database: the "migration" has already been applied. The timestamp in the file name is used for sorting

Now, change the model, add a Url property to the Blog class

 Public classBlog { Public intBlogId {Get;Set; }  Public stringName {Get;Set; }  Public stringURL {Get;Set; }  Public VirtualList<post> Posts {Get;Set; } }
    • run   in Package Manager console; Strong style= "line-height:1.5;" >add-migration addurl   Command
      The

       add-migration command checks for changes since the last migration and builds a new migration with all the changes. We can specify a name for the migration; In this case, this migration is called "Addurl". The code that the
      builds shows that we need to be to dbo. The Blogs table adds a URL column that can hold string data. If you want, you can edit the built code, but, in this case, it is not necessary.

       namespace  blogsolution.migrations{using  System;        Using  System.Data.Entity.Migrations; public partial class  addurl:dbmigration {public override void  up () {AddColumn ( "dbo. Blogs "," Url ", c =>  c.string ()); public override void  down () {Dropcolumn ("dbo. Blogs "," Url "); } }}
    • Run the update-database command in the Package Manager console. This command applies all pending migrations to the database. Initialcreate migrations are already applied, so these migrations will only apply the new addurl migration.
      Tip: You can use the –Verbose switch when you call the Update-database command to view the SQL that is executed against the database.

The new URL column has been added to the Blogs table in the database:

6. Data annotations

So far, EF has discovered a model that uses its default conventions. However, sometimes classes do not conform to conventions, and we need to be able to perform further configuration.

There are two ways to do this: 1, data annotations (how to use data annotations to supplement or rewrite content detected by convention), 2, fluent API (via the Code first fluent API)

  • add user class to model
     public  class   User { public  string  Username {get ; set       public  string  DisplayName {get ; set  
  • Add a set to a derived context
     Public class Bloggingcontext:dbcontext {     publicgetset;}       Public Get Set ; }       Public Get Set ; } }
  • If you try to add a migration, you receive the error message "EntityType ' User ' does not have a key defined. Please define the key for the EntityType. " This is because EF cannot know that the Username should be the user's primary key."
  • We'll use the data annotations, so we need to add a using statement at the top of the Program.csusing System.ComponentModel.DataAnnotations;
  • Now, note the Username property, which identifies it as the primary key
     Public class User {     [Key]     publicstringgetset;       Public string Get Set ; } }
  • Use the add-migration AddUser command to build a migration that applies these changes to the database
  • Run the update-database command to apply the new migration to the database

The full list of comments supported by EF is:

    • Keyattribute
    • Stringlengthattribute
    • Maxlengthattribute
    • Concurrencycheckattribute
    • RequiredAttribute
    • Timestampattribute
    • Complextypeattribute
    • Columnattribute
    • Tableattribute
    • Inversepropertyattribute
    • Foreignkeyattribute
    • Databasegeneratedattribute
    • Notmappedattribute

7. Fluent API

Most model configurations can be made using simple data annotations. The Fluent API is a more advanced approach that allows you to specify a model configuration that contains all the features of the data annotations, in addition to the more advanced configurations that some data annotations cannot support. Data annotations and the Fluent API can be used together.

To access the Fluent API, you need to override the Onmodelcreating method in DbContext. Suppose we need to rename the column that User.displayname stores to display_name.

  • Use the following code to override the Onmodelcreating method of Bloggingcontext
     Public classBloggingcontext:dbcontext { PublicDbset<blog> Blogs {Get;Set; }  PublicDbset<post> Posts {Get;Set; }  PublicDbset<user> Users {Get;Set; } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {modelbuilder.entity<User>()             . Property (U=u.displayname). Hascolumnname ("Display_name"); } }
  • Use the add-migration changedisplayname command to build the migration to apply these changes to the database
  • Run the update-database command to apply the new migration to the database

The DisplayName column is now renamed to Display_name:

Entity Framework uses the database through code first

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.