Entityframework 2-Ef Development Mode

Source: Internet
Author: User
Tags management studio sql server management studio connectionstrings

I haven't written about EF for a long time, and I feel unfamiliar with it. Recently, EF5 was released. I learned some new knowledge and summarized it.

1.Review of Entity Framework Architecture Principles

What is EF: entityframework is an open-source ORM (Object relationship ing) Framework of Microsoft. It is a data storage technology promoted by Microsoft and is often used to build a data storage layer, allows applications to access the content of a relational database as an object model.

The architecture and principle of EF: the core content of EF is EDM. For details, refer to the previous article. It can be understood as an ADO. net enhanced version. Its bottom layer is ADO. net provider, the upper layer is the application, which provides more flexible, simpler and more convenient data access methods.

Advantages of EF: it is an open-source framework that supports multiple databases (currently it seems that SQL Server is the most stable, and Oracle's support has never been perfect ), separates applications from databases, and supports multiple development modes.

EF disadvantages: it is in ADO. net, and the performance is better than that of ADO. net has some losses, but as long as EF is used properly to avoid the loss caused by some inferior query statements, EF performance can be effectively improved.

2.Entity Framework Development Mode

EF provides four development modes:

Code first (New Database): defines the class and ing relationships in the code, generates a database using the model, and updates the database using the migration technology.

Code first (existing database): defines the class and ing relationships in the Code and provides tools for reverse engineering.

Model first: create a model in the designer and use the model to generate a database. All classes are automatically generated by the model.

Datebase first: In the designer, the model is generated reversely, and all classes are automatically generated by the model.

We may not understand how to use these four development modes. Here we will analyze them one by one.

2.1 database first Mode

The earliest development mode used by EF is also the simplest development mode. It uses an existing database to reverse analyze the model and obtain class information. The advantage of this method is that the development is simple and easy to manage. The inconvenience is that it limits the developer's modifications to the model. Of course, EF also provides new features in version 4.0 to support pocos, this allows developers to conveniently operate databases. Information about pocos can look at a series of http://blogs.msdn.com/ B /adonet/archive/2009/05/21/poco-in-the-entity-framework-part-1-the-experience.aspx

Usage:

1. In the vs project, right-click --- add --- new item --- data, and select ADO. Net Object Data Model

2. Select "generate from database"

3. Select the database engine and database to be connected, and select the objects to be included.

2.2 model first Mode

This mode is rare in practical applications. If you create a small database model, you can try this method. It requires us to define the model in vs design and then create a database through the model.

Usage:

1. Add an ADO. Net object data model and select "Empty model"

2. Right-click the designer of the model -- add -- entity

2. Enter the Object Name and attributes.

3. Right-click the object and choose "add"> "scalar property". Enter the attribute name.

4. Repeat the preceding steps to create several entities, right-click the blank space of the designer -- add -- join, and enter the association name, link object, and ing.

5. right-click the blank area of the designer-generate a database based on the model and follow the wizard prompts to complete the creation. Finally, an SQL script is obtained, which is placed in SQL Server Management studio for execution, the database is created.

I personally think model first is a bit similar to Power Designer modeling.

2.3 code first-new database mode

This mode is suitable for small and medium-sized projects, and the code is relatively simple and refreshing. However, code first is troublesome for database updates. First, let's see how code first is used.

1. Create some classes we need

 public class Blog    {        public int BlogId { get; set; }        public string Name { get; set; }        public string Url { get; set; }        public virtual List<Post> Posts { get; set; }    }    public class Post    {        public int PostId { get; set; }        public string Title { get; set; }        public string Content { get; set; }        public int BlogId { get; set; }        public virtual Blog Blog { get; set; }    }    public class User    {        [Key]        public string Username { get; set; }        public string DisplayName { get; set; }    }

2. Create a class that inherits dbcontext. In this class, you must use dbset to place the class we just created in the object set.

public class BloggingContext : DbContext    {        public DbSet<Blog> Blogs { get; set; }        public DbSet<Post> Posts { get; set; }        public DbSet<User> Users { get; set; }    }

3. A bloggingcontext instance can be operated and saved using the savechanges method.

BloggingContext db = new BloggingContext();Console.Write("Enter a name for a new Blog: ");var name = Console.ReadLine();var blog = new Blog { Name = name };db.Blogs.Add(blog);Random ran=new Random();User user = new User();user.Username = "user" + ran.Next(1, 1000);user.DisplayName = "display name for " + user.Username;db.Users.Add(user);db.SaveChanges();

4. run SQL Server Management Studio (sqlexpress must exist) to view the newly created database and find it named "dbcontext namespace. dbcontext class name".

5. We can establish the database elsewhere through some means.

Modify the following information in APP. config:

<configuration><connectionStrings><add name="BloggingCompactDatabase"providerName="System.Data.SqlServerCe.4.0"connectionString="Data Source=Blogging.sdf"/></connectionStrings></configuration>

Modify the bloggingcontext Constructor

public class BloggingContext : DbContext { public BloggingContext() : base("BloggingCompactDatabase") { } }

 

Of course, you can also directly modify bloggingcontext without using app. config.

 

public class BloggingContext : DbContext {       public BloggingContext(string conn) : base(conn)      {     } }

Then, when you call bloggingcontext, directly upload the connection string.

Supplement: code first sets the primary and Foreign keys and field attributes.

In the previous two design methods, you can easily set the primary and Foreign keys and field attributes of the data table. For the first reason, it is troublesome to directly set the data table using code. But in fact, we can use the atrribute mechanism of c # to complete these settings.

Example 1: ID is the primary key, auto Increment

[Key,DatabaseGenerated(DatabaseGeneratedOption.None)]public int ID { get; set; }

Example 2: Name is required and the maximum value is 50.

[Required]  [MaxLength(50)]  public string Name { get; set; }  

For more information about how codefirst establishes a data table relationship, see http://www.cnblogs.com/Gyoung/archive/2013/01/22/2869782.html.

2.4 code first-existing database mode

You can use EF powertools to reverse generate all the tables in the database and then use them with application modifications. However, in EF5, EF powertools is still in the testing stage, so we will not introduce this method further here.

 

3. Use code firstHow to update the database after the Development Mode

We can see that in code first, the database model is built through the code and then the database is generated. If the database structure is required to change (adding attributes or classes and renaming attributes and classes, rename a column or table and delete the attribute.

), The entity class has changed, and we need to update the database through some methods.

For example, in the code first example, change the name of the blog class to username and run the command. An error is reported:

 

At this time, we need to update the database:

1. Install nuget of. Open the nuget console and enter enable-migrations to enable database migration. If it is enabled, the console will prompt "migrations have already been enabled in project '***'. to overwrite the existing migrations configuration, use the-force parameter ."

2. Mark the migration point, enter add-migration ***, And the asterisk is the migration point name, which can be customized.

3. Enter Update-database to complete the update.

If you run the program again, no errors will be reported and the database is updated. To roll back to a migration point, enter Update-database-targetmigration: "***" in the nuget console as the Migration point name. In addition, scripts can be generated using script parameters, such as update-database-script-sourcemigration: "**"-targetmigration: "**". In this way, an SQL script is generated instead of updating the database directly.

 

Of course, you can use the automatic migration function if you think it is inconvenient to run too many commands on the console. The method is as follows:

1. Open configuration. CS in the migrations folder and modify the code

  public Configuration()        {            AutomaticMigrationsEnabled = true;        }

2. to update the database, you only need to enter Update-database in the nuget console. If the message "automatic migration was not applied because it wocould result in data loss" is displayed

Add the-force parameter after Update-database. Note that this will not cause data loss.

 

The above is a summary of the EF development model, and detailed issues will be introduced in the future.

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.