Entity Framework Database First, entityframework
Entity Framework> Get Started> Database First
Prerequisites
To complete this walkthrough, you must install Visual Studio 2010 or Visual Studio 2012.
If you are using Visual Studio 2010, you also need to install NuGet.
1. Create an existing database
Generally, it is intended for an existing database, but in this walkthrough, we need to create a database for access.
The database server installed with Visual Studio varies with the installed Visual Studio version:
- If Visual Studio 2010 is used, an SQL Express database is created.
- If Visual Studio 2012 is used, the LocalDb database is created.
We continue to generate the database.
- Open Visual Studio
- "View"-> "server resource manager"
- Right-click "Data Connection"-> "add connection ..."
- If you have not connected to the database from the Server resource manager, you must select Microsoft SQL Server as the data source.
- Connect to LocalDb ((Localdb) \ v11.0) Or SQL Express (. \ SQLEXPRESS).DatabaseFirst. BloggingDatabase Name
- Select "OK". The system will ask if you want to create a new database and select "yes"
- The new database appears in the server resource manager. Right-click the database and select "new query"
- Copy the following SQL statement to the new query, right-click the query, and select "run"
CREATE TABLE [dbo].[Blogs] ( [BlogId] INT IDENTITY (1, 1) NOT NULL, [Name] NVARCHAR (200) NULL, [Url] NVARCHAR (200) NULL, CONSTRAINT [PK_dbo.Blogs] PRIMARY KEY CLUSTERED ([BlogId] ASC) );
CREATE TABLE [dbo].[Posts] ( [PostId] INT IDENTITY (1, 1) NOT NULL, [Title] NVARCHAR (200) 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 generate a basic console application that uses Database First to perform data access:
- Open Visual Studio
- "File"-> "new"-> "project ..."
- Select Windows and console applications from the menu on the left"
- InputDatabaseFirstSampleAs name
- Select "OK"
3. Reverse Engineering of the Model
We use the Entity Framework designer in Visual Studio to create a model.
- "Project"-> "Add new project ..."
- Select "data" from the menu on the left, and then select "ADO. NET Object Data Model"
- InputBloggingModelAs the name, and then click "OK"
- This will start the Object Data Model Wizard
- Select "generate from database" and click "Next"
- Select the database created in the first part, and enterBloggingContextAs the name of the connection string, and then click "Next"
- Click the check box next to the table to import all tables, and then click Finish"
After the reverse engineering process is completed, the new model is added to the project and opened in the Entity Framework designer for viewing. The project also adds an App. config file containing the connection details of the database.
Other steps in Visual Studio 2010
If Visual Studio 2010 is used, perform other steps to upgrade to the latest version of the object framework. The upgrade is very important, because after the upgrade, you can access the improved API diagram and the latest Bug fixes. The improved API diagram is more convenient to use.
First, you need to obtain the latest version of the object framework from NuGet.
- "Project"-> "manage NuGet packages ..."
If the "manage NuGet packages..." option is not available, the latest version of NuGet should be installed.
- Select the "online" tab
- Select the "EntityFramework" Package
- Click "Install"
Next, we need to exchange the model to generate the DbContext API Code introduced in earlier versions of the Entity Framework.
- In the EF designer, right-click an empty location on the model and select "Add code generation item ..."
- Select "online template" from the menu on the left and search for "DbContext"
- Select "EF 5.x DbContext Generator for C #" And enter the name.BloggingModelAnd then click "add"
4. Read and Write Data
We already have a model. Now we can use the model to access some data. Classes used to access data are automatically generated based on EDMX files.
This screen snapshot is from Visual Studio 2012. If Visual Studio 2010 is used, the BloggingModel. tt and BloggingModel. Context. tt files are directly located under the project rather than nested under the EDMX file.
Implement the Main method in program. cs as follows. These codes create a new instance for the context and use the instance to insert a new blog. Then, it uses LINQ to query and retrieve all the blogs in the database (sorted alphabetically by titles ).
class Program { static void Main(string[] args) { using (var db = new BloggingContext()) { // Create and save a new Blog Console.Write("Enter a name for a new Blog: "); var name = Console.ReadLine(); var blog = new Blog { Name = name }; db.Blogs.Add(blog); db.SaveChanges(); // Display all Blogs from the database var query = from b in db.Blogs orderby b.Name select b; Console.WriteLine("All blogs in the database:"); foreach (var item in query) { Console.WriteLine(item.Name); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } }
Now, you can run the application and test it.
Enter a name for a new Blog: ADO. NET BlogAll blogs in the database: ADO. NET Blog Press any key to exit...
5. Process Database changes
Currently, you can make some changes to the database architecture. When making these changes, you also need to update the model to reflect these changes.
The first step is to make some changes to the database architecture. We will add a user table to the schema.
- In server resource manager, right-clickDatabaseFirst. BloggingDatabase, and then select "new query"
- Copy the following SQL statement to the new query, right-click the query, and select "run"
CREATE TABLE [dbo].[Users] ( [Username] NVARCHAR(50) NOT NULL PRIMARY KEY, [DisplayName] NVARCHAR(MAX) NULL )
After the architecture is updated, use these changes to update the model.
- In the EF designer, right-click an empty location on the model and select "update model from database...". This will start the Update Wizard.
- On the "add" tab of the Update Wizard, select the box next to the "table", which means you need to add a new table from the schema.
The "refresh" tab displays all existing tables in the model. During the update, the system checks whether these tables have changed. The delete tab displays all tables that have been deleted from the schema and will be deleted from the Model during the update. Information about these two tabs is automatically detected and provided for reference purposes only. You cannot change any settings.
- Click Finish in the Update Wizard"
Model updates, including ing to the new User entity of the User table that we have added to the database.
Summary
This walkthrough describes Database First development. Through this development, you can create models based on existing databases in the EF designer. Then, we use the model to read and write some data from the database. Finally, we update the model to reflect changes to the database architecture.