Entity Framework Database First

Source: Internet
Author: User
Tags visual studio 2010

Entity Framework > Get Started > Database First

Required conditions

To complete this walkthrough, you need to install Visual Studio 2010 or Visual Studio 2012.

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

1. Create an existing database

Typically, you are targeting an existing database that has already been created, but in this walkthrough we need to create a database for access.

The database server installed with Visual Studio differs depending on the version of Visual Studio that is installed:

    • If you are using Visual Studio 2010, you will create a SQL Express database.
    • If you are using Visual Studio 2012, you will create a LocalDb database.

We continue to build the database.

    • Open Visual Studio
    • View, Server Explorer
    • Right-click "Data Connection", "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 LocalDb ((LocalDb) \v11.0) or SQL Express (. \SQLExpress), depending on the installed database, and then enter Databasefirst.blogging as the database name
    • Select OK and the system will ask if you want to create a new database and select Yes
    • The new database now appears in Server Explorer, right-click the database, and select New query
    • Copy the following SQL to the new query, right-click the query, and select Execute

CREATE TABLE [dbo].[Blogs] (     [BlogId] INT IDENTITY(1,1) not NULL,     [Name] NVARCHAR( $)NULL,     [URL]  NVARCHAR( $)NULL,     CONSTRAINT [pk_dbo. Blogs] PRIMARY KEY CLUSTERED([BlogId] ASC) ); 
CREATE TABLE [dbo].[Posts] (     [PostID] INT IDENTITY(1,1) not NULL,     [Title] NVARCHAR( $)NULL,     [Content] NTEXT NULL,     [BlogId] INT  not NULL,     CONSTRAINT [pk_dbo. Posts] PRIMARY KEY CLUSTERED([PostID] ASC),     CONSTRAINT [fk_dbo. Posts_dbo. Blogs_blogid] FOREIGN KEY([BlogId])REFERENCES [dbo].[Blogs]([BlogId]) on DELETE CASCADE );

 
2. Create an application

For simplicity, we will build a basic console application that uses database first to perform data access:

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

3. Reverse engineer The Model

We use the Entity Framework designer in Visual Studio to create the model.

    • Project, add New Item ...
    • Select data from the left-hand menu and select the ADO Entity Data Model
    • Enter Bloggingmodel as the name, and then click OK
    • This launches the Entity Data Model Wizard
    • Select build from database, and then click Next
    • Select Connect to the database created in the first section, enter Bloggingcontext as the name of the connection string, and then click Next
    • Click the check box next to table, import all the tables, and then click Finish

After the reverse engineering process is complete, the new model is added to the project and opened in the Entity Framework Designer for viewing. An app. config file is also added to the project that contains the connection details for the database.

Additional steps in Visual Studio 2010

If you are using Visual Studio 2010, you need to perform some additional steps to upgrade to the latest version of the Entity Framework. Upgrading is important because the improved API surface and the latest Bug fixes can be accessed after the upgrade, and the improved API surface is more convenient to use.

First, you need to get the latest version of the Entity Framework from NuGet.

    • "Project" –> "Manage NuGet packages ..."
      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"

Next, you need to swap the model to generate code that leverages the DbContext API introduced in earlier versions of the Entity Framework.

    • In the EF designer, right-click the empty location on the model and select Add code generation Item ...
    • Select Online Templates from the left menu and search for "DbContext"
    • Select "EF 5.x DbContext Generator for C #", enter the name Bloggingmodel, and click "Add"

4. Read and write Data

Now that we have the model, we can use the model to access some of the data. The class used to access the data is automatically generated based on the EDMX file.

This screenshot comes from Visual Studio 2012, and if you are using Visual Studio 2010, the Bloggingmodel.tt and BloggingModel.Context.tt files are located directly under the project, not nested in the EDMX File below.

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. It then 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 a name for a new Blog:"); varName =Console.ReadLine (); varBlog =NewBlog {Name =name}; Db.             Blogs.add (blog); Db.              SaveChanges (); //Display all Blogs from the database            varquery = fromBinchdb. Blogs byB.nameSelectb; Console.WriteLine ("All blogs in the database:"); foreach(varIteminchquery) {Console.WriteLine (item.             Name); } Console.WriteLine ("Press any key to exit ...");         Console.readkey (); }     } }

You can now run the application and test it.

Exit...

5. Working with database changes

You can now make some changes to the database schema, and when you make these changes, you need to update the model to reflect those changes.

The first step is to make some changes to the database schema. We will add a user table to the schema.

    • In Server Explorer, right-click the databasefirst.blogging database and select New query
    • Copy the following SQL to the new query, right-click the query, and select Execute
CREATE TABLE [dbo].[Users] (     [Username] NVARCHAR( -) not NULL PRIMARY KEY,      [DisplayName] NVARCHAR(MAX)NULL )

After you update the schema, use these changes to update the model.

    • In the EF designer, right-click the empty location on the model and select Update model from Database ..., which starts the Update Wizard
    • On the Add tab of the Update Wizard, select the box next to table, which indicates that a new table needs to be added from the schema.

      The Refresh tab displays all existing tables in the model, and during the update, the tables are checked for changes. The Delete tab shows all tables that have been removed from the schema and will also be removed from the model during the update. Information about these two tabs is automatically detected and provided for informational purposes only and you cannot change any settings.

    • Click Finish on the Update Wizard

The model is updated, including the new user entity that maps to the users table that we have added to the database.

Summary

This walkthrough introduces database first development, which allows you to create a model based on an existing database in the EF designer. We then use the model to read and write some data from the database. Finally, we update the model to reflect changes made to the database schema.

Entity Framework Database 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.