Entity Framework7 The full function of getting started. NET version with EF7 (including source) data migration common error handling

Source: Internet
Author: User
Tags dotnet

Entity Framework7 The full function of getting started. NET (Console, WinForms, WPF, etc.) using EF7

Yesterday, we introduced the new features and development plans for EF, and if you don't understand, what's the difference between Entity Framework7? How far has it been developed? Today, we are open to learning full-featured. NET (full. NET) using EF7. The official has written about the latest pre-release version of Ef7.0.0-beta7 's introductory tutorial, very detailed, I do not need to repeat the wheel, just because it is English, in order to facilitate a lot of lazy people (not to read English, is to look at English do not want to look down, nameless feel complex. Another point is not willing to go to foreign sites to find information, special to make a simple translation. If you are not lazy, please steady (the original address: http://ef.readthedocs.org/en/latest/getting-started/full-dotnet.html), help me to see what is wrong with the place, welcome correction Thank you!

In this article, we will build a console application that uses EF7 to perform basic data access. You will see the following points of knowledge in this article:

1. Install NuGet 2.8.6 or later;

2, create a new project;

3. Installation of the Entity Framework (EF7.0.0-BETA7);

4, create the model;

5, create the database;

6, the use of models;

You can view an example of this article on GitHub: Https://github.com/aspnet/EntityFramework.Docs/tree/master/docs/getting-started/full-dotnet/sample

Note: The version used in this article is Ef7.0.0-beta7, which is the latest pre-release version available on nuget.org. You can get a compiled version of the latest code in https://www.myget.org/F/aspnetvnext/api/v2/. The code changes too quickly and we don't maintain the latest documentation for the Getting Started tutorial.

One, install NuGet 2.8.6 or later

installation of EF7 requires NuGet2.8.6, or a higher version. After you install the update, restart your visual Studio.

1, Visual Studio 2015 does not need to install, because it already contains a compatible version;

2. Visual Studio 2013 Please install the latest nuget version for VS2013;

3. Visual Studio 2012 Please install the latest nuget version for VS2012;

Note: The NuGet version number can be confusing, and what we need is the 2.8.6 Extended version 2.8.60610.xxx.

Second, create a new project

1. Open Visual Studio (this article uses Visual Studio 2015, you can use VS2012 and above);

2. New (project), document (file) ...

3. Select Template->visual c#->windows; from the left menu

4, select the console Application (console application) project template;

5, choose. NET4.5 or higher. NET Framework;

6, give your project name, then click OK (OK);

III. installation of the entity FrameWork

In order to use EF7, you have to install the database and the provider (Provider) you want to use, and this article uses SQL Server. The following is a list of database Provider available under EF7.

1, Entityframework.sqlserver
2, Entityframework.sqlite
3, Entityframework.inmemory
4, ENTITYFRAMEWORK.SQLSERVERCOMPACT40
5, Entityframework.sqlservercompact35
6, Entityframework.npgsql

A. Select Tools->nuget Package Manager (Nuget Package Manager) on the Menu->package Manager Console (Package Manager console);

B, run the command "install-package entityframework.sqlserver–pre"

Because we are going to use the Entity Framework's related commands later in this article to maintain the database, we now have to install the command packages (Commands package).

C, run the command "install-package entityframework.commands–pre";

Iv. Creating Models

Now it's time to define a context and entity class to build the model.

1. Project->add Class (Add Class) ...;

2. Type Modle.cs as the class name and click OK (OK);

3, replace the contents of the file with the following code;

  Note: The Onconfiguring method (new in EF7) is used to define the provider used, and other optional configurations .

1 usingMicrosoft.Data.Entity;2 usingSystem.Collections.Generic;3 4 namespaceEfgetstarted.consoleapp5 {6      Public classBloggingcontext:dbcontext7     {8          PublicDbset<blog> Blogs {Get;Set; }9          PublicDbset<post> Posts {Get;Set; }Ten  One         protected Override voidonconfiguring (Dbcontextoptionsbuilder optionsbuilder) A         { -             //Visual Studio 2015 | LocalDB 12 instance created with Visual Studio -Optionsbuilder.usesqlserver (@"server= (localdb) \mssqllocaldb;database=efgetstarted.consoleapp; Trusted_connection=true;"); the  -             //Visual Studio 2013 | LocalDB 11 instance created with Visual Studio -             //optionsbuilder.usesqlserver (@ "server= (localdb) \v11.0;database=efgetstarted.consoleapp; Trusted_connection=true; "); -  +             //Visual Studio 2012 | SQL Express instance created with Visual Studio
- //optionsbuilder.usesqlserver (@ "SERVER=.\SQLEXPRESS;DATABASE=EFGETSTARTED.CONSOLEAPP; Trusted_connection=true; "); + } A at protected Override voidonmodelcreating (ModelBuilder ModelBuilder) - { - //Configure Blog.url to required -Modelbuilder.entity<blog>() -. Property (b =B.url) - . Required (); in } - }
    // blog to    Public classBlog + { - Public intBlogId {Get;Set; } the Public stringURL {Get;Set; } * $ PublicList<post> Posts {Get;Set; }Panax Notoginseng } -    // articles the Public classPost + { A Public intPostID {Get;Set; } the Public stringTitle {Get;Set; } + Public stringContent {Get;Set; } - $ Public intBlogId {Get;Set; } $ PublicBlog Blog {Get;Set; } - } -}

v. Create a database

Once you have the model, you can use data migration (migrations) to create the database.

1. Select Tools->nuget Package Manager (Nuget Package Manager) on the Menu->package Manager Console (Package Manager console);

2. Execute the command "Add-migration myfirstmigration" to create a migration bracket (scaffold) for the model just created;

3. Execute the command "update-database" to apply a migration to the database. Because the database does not exist, it will create a database for you before the app migrates;

  Tip: If you have modified the model, use the command "add-migration" bracket (scaffold) to apply the appropriate modifications using a new migration. Once you have checked and confirmed the generated stand (scaffold) code, use the command "update-database" to apply these modifications to the database.

Vi. Use of models

You can now use the model to perform data access.

1, open the file Program.cs;

2, replace the contents of the file with the following code;

1 usingSystem;2 3 namespaceEfgetstarted.consoleapp4 {5     class Program6     {7         Static voidMain (string[] args)8         {9             using(vardb =NewBloggingcontext ())Ten             { OneDb. Blogs.add (NewBlog {URL ="http://blogs.msdn.com/adonet" }); A                 varCount =db. SaveChanges (); -Console.WriteLine ("{0} Records saved to database", count); -  the Console.WriteLine (); -Console.WriteLine ("All Blogs in database:"); -                 foreach(varBloginchdb. Blogs) -                 { +Console.WriteLine ("-{0}", blog. URL); -                 } +             } A         } at     } -}

2, Debug->start without Debugging (do not debug);

You will see a blog is saved in the database, and in the console to play out the details of the blog,

As you can see, the use of the Data Migration command, with the widespread use of code-first, I believe that the opportunity to use it more and more, I have to use my own common problems encountered in sharing to everyone.

An exception that resembles the following:

Enable-migrationsenable-migrations: The "enable-migrations" item cannot be identified as a cmdlet, function, script file, or name of a running program. Check the spelling of the name, if the path is included, make sure the path is correct, and then try again. Location Line: 1 characters: 1+ enable-migrations+ ~~~~~~~~~~~~~~~~~ + categoryinfo:objectnotfound: (enable-migrations:string) [], Comma Ndnotfoundexception + fullyqualifiederrorid:commandnotfoundexception.

The causes of this problem are generally as follows:

1, the input of the underlined "-" format is not correct, check whether it is full-width input, mistakenly entered the underscore "_", or there are spaces before and after;

2. Do not refer to the EntityFramework command, please perform the following name (Import-module project Path \packages\entityframework.6.1.3 (EF version) \tools\ ENTITYFRAMEWORK.PSD1)

It is also important to note that when you execute a command, the default project must select the project that contains the model.

Speaking of recommendation, and reading, I have a not understand the place, why, what this sentiment, that experience of the article will have a very high reading volume and recommended number? Some of the better-written blogs (such as some of the DDD articles written by Daniel) have only hundreds of of the reading volume. Did we. NET developers lack of technology, is the soul of chicken soup? Why is it? Can you tell me?

  

Say so much today, thank you for reading!

Entity Framework Exchange QQ Group: 458326058, welcome interested friends to join the exchange

Thank you for your continued attention, my blog address: http://www.cnblogs.com/VolcanoCloud/

Entity Framework7 The full function of getting started. NET version with EF7 (including source) data migration common error handling

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.