To create a code-based model that maps to an existing database by using codes-a database

Source: Internet
Author: User
Tags connectionstrings

Prerequisite

1. Install Visual Studio or Visual Studio 2013

2, install the Entity Framework Tools for Visual Studio 6.1 or later. Installs the EF reference get Entity Framework.

One, prepare a database

The database in this article is named Blogging.

Second, create an application

For the sake of simplicity, this article creates a console application that accesses data using the code-one method. The console application name is:codefirstexistingdatabasesample.

Three, reverse engineering model

We will use the entity Framework Tools for Visual Studio to help us generate the initial code that matches the database. This tool is only used to generate code, and of course it can be written by hand. The steps are as follows:

1, the project-> add new items

2, select "Data", then, select "ADO." NET Entity Data Model "

3, name input bloggingcontext, click OK

4. Start the Entity Data Model Wizard

5, select "Generate from the database", click Next, as shown.

6, select you have created a good database connection, click Next

7, select the table, click to complete

When the reverse engineering model is complete, some items are added to the project, so let's take a look at which items are added.

Iv. items added to the reverse engineering model

1. configuration file

A app.config file has been added to the project, which contains a connection string that connects to an existing database.

<connectionStrings>
<add
name= "Bloggingcontext"
connectionstring= "Data source= (localdb ) \v11.0;initial catalog=blogging;integrated security=true; Multipleactiveresultsets=true; App=entityframework "
providername=" System.Data.SqlClient "/>
</connectionStrings>
You will also see other settings in the configuration file, which are the default settings for EF when you create the database in code-mode. Because we are mapping to an existing database, these settings will be ignored in the application.

2, the derivation of the context

A Bloggingcontext class has been added to the project. The context represents a session with the database that allows us to query and save data.

In our model, the database context exposes a dbset<tentity>for each type. You will also notice that the default constructor in the class invokes a base constructor using the "Name=" syntax, which tells the code the single connection string to use the connection string in the configuration file.

public partial class bloggingcontext : dbcontext      {          public bloggingcontext ()                : base ("Name=bloggingcontext")            {          }             public virtual DbSet<Blog> Blogs { get;  set; }          public virtual dbset<post > Posts { get; set; }             Protected override void onmodelcreating (dbmodelbuilder modelbuilder)            {          }       } 
When you use the connection string in the configuration file, you must use the "Name=" method. This ensures that if the connection string does not exist, the EF throws an error instead of creating a new database by convention.

3, Model class

Finally, the blog and post classes are added to the project. These classes are domain classes and form the model. The data annotations of these classes can reassign the conventions that code number A does not match the existing database structure. For example, theblog.name and blog.url properties have stringlength annotations because the maximum length of these two fields in the database is the Code The maximum default length is the maximum length that the database can support, in SQL Server nvarchar (max).

public partial class Blog
{public
blog ()
{
Posts = new hashset<post> ();
public
int BlogId {get; set;}
[Stringlength]
public string Name {get; set;}
[stringlength] public
string Url {get; set;}
Public virtual icollection<post> Posts {get; set;}
}

V. Reading and writing data

Now use model to access the data. The execution results are displayed by executing the Main method in Program.cs . This code creates the context of a new instance and then uses it to insert a new blog. It then uses a LINQ query to retrieve all blogs from the database in alphabetical order by title.

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); &nbSp             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 ( );          }      } }
Run the application now to test. The results are as follows:

Enter a name for a new Blog:ADO.NET Blog
All blogs in the database:
. NET Framework Blog
Ado.net Blog
The Visual Studio Blog
Press any key to exit ...


Other issues

1. Custom Build Code

For more information, see: Customizing Code a Existing Database

2, the database changed, how to modify model

The class generated by Code-A can be adjusted and modified. If the database has changed, you can edit the class manually or perform the reverse engineering rewrite class again.

3. Use code-I migration to existing databases

See: Code I migrations with an existing database

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.