Ef1:mvc/ef (Entity Framewok)/first migrations

Source: Internet
Author: User
Tags connectionstrings

1. Concept

  Entity Framework: The ADO Entity Framework is an object-relational (O/R Mapping) solution developed by Microsoft on the basis of ADO. (This is only a database application that understands. NET Features Program (O/R mapping), such as Hibernate, is not in-depth here, pending additional learning later. In short, Microsoft has helped you connect the database is an Entity Framework, so that you can operate more convenient, not too much to write SqlHelper and LINQ statement LAMDA expression and so on, to improve the development efficiency.

  First migrations: . Net Database Migration Tool for database management applications in conjunction with EF.

2. Run the database through the project

1. Database connection configuration. Add a database connection in Project Web. config related to:

<connectionStrings>  <add name= "defaultconnection"        connectionstring= "Data source= (LocalDb) \v11.0 ; Initial catalog=aspnet-mvcmovie-2012213181139;integrated security=true "        providername=" System.Data.SqlClient "   />      <add name=" Moviedbcontext "        connectionstring=" Data source= (LocalDB) \v11.0; attachdbfilename=| datadirectory|\movies.mdf;integrated security=true "        providername=" System.Data.SqlClient "   /> </ Connectionstrings>

2. First construct the entity class and the context association, such as the class code in 3.

3. Run private Portalcontext db = new Portalcontext () from the project code and generate the database automatically. Common Beginner Tutorial MVC

To generate an example by using control:

The Microsoft MVC Tutorial generates movie additions and deletions by using the control template and related actions.

Note: In order to continue learning 3 first migrations Data migration, delete the App_Data database file *.mdf.

3. First Migrations Application Example
    • To produce a Database entity association

The entity classes (corresponding tables) and context associations need to be constructed first, with the following code:

Using system;using system.collections.generic;using system.data.entity;using system.linq;using System.Web;namespace mvceftest.models{public    class Movie    {public        int ID {set; get;}        Public String Name {set; get;}        Public Double price {set; get;}        public int level {set; get;}    }    public class people    {public        int ID {set; get;}        Public String Name {set; get;}        public int year {set; get;}    }    public class Portalcontext:dbcontext    {        ///static constructor, set when the database model changes, delete the current database, and rebuild the new database.        //static portalcontext ()        //{        //    Database.setinitializer (new Dropcreatedatabaseifmodelchanges<portalcontext> ());        Public        dbset<movie> Movies {get; set;}        Public dbset<people> peoples {get; set;}}   }

Click "Tools/Library Package Manager/Package Management Console" to open the package management console:

If the Entity Framework is not added, first install the Entity Framework:

Pm> Install-package EntityFramework

Perform

Pm> enable-migrations-enableautomaticmigrations
The Code first migration has been enabled for Project Mvceftest.

The execution succeeds, the Migrations folder is added to the project, and the class file Configuration.cs is generated. The code is as follows namespace Mvceftest.migrations

 {using System;    Using System.Data.Entity;    Using System.Data.Entity.Migrations;    Using System.Linq; Internal sealed class Configuration:dbmigrationsconfiguration<mvceftest.models.portalcontext> {public C        Onfiguration () {automaticmigrationsenabled = true; } protected override void Seed (MVCEFTest.Models.PortalContext context) {//This method would be            Called after migrating to the latest version. You can use the Dbset<t>. AddOrUpdate () Helper extension method//To avoid creating duplicate seed data.            e.g. Context.            People.addorupdate (//P = = p.fullname,//new Person {FullName = "Andrew Peters"},            New Person {FullName = ' Brice Lambson '},//new Person {FullName = ' Rowan Miller '}            //    ); 

} } }

Seed executes code for initialization, as can be done through the context. People.addorupdate add data.

    • Data database Entity (O/R mapping) modification   

pm> add-migration Initial
Scaffolding is being built for migrating "initial".
The designer code for this migration file contains a snapshot of the current Code first model. This snapshot is used to calculate changes to the model the next time the migration scaffolding is built. If you make other changes to the model that you want to include in this migration, you can re-build the scaffolding by running Add-migration 201601120840091_initial again.
Pm>

Generate 201601120840091_initial.cs in the Migrations folder.

    • Database synchronization (Data migration)
pm> update-database-verboseusing StartUp project ' Mvceftest '. Using NuGet project ' mvceftest '. Specify the "-verbose" tag to view the SQL statements applied to the target database. The target database is: "MVCEFTest.Models.PortalContext" (Data Source: (LOCALDB) \v11.0, provider: System.Data.SqlClient, Source: Convention). There are no pending code-based migrations. The seed method is running.
4. Error logging

Applying an instance of a local SQL Server application, after the first build is finished, removing the MDF, the rebuild sometimes results in the form of various database link errors.

Most such as, connectstring error, *.mdf cannot find, because the local backup left or the name does not correspond and so on. The "View/sql Server Manager" can be removed/added (if there is a legacy please delete, if no re-add) operation resolves, verified:

Open the SQL Object Explorer for vs2013,

Delete (LocalDb) The database that already exists under the \v11.0 server

(LocalDb) \v11.0 If it does not exist, add it first, and then delete the database below it.

Ef1:mvc/ef (Entity Framewok)/first migrations

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.