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

Source: Internet
Author: User
Tags dotnet

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.sqlservercom PACT40 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.

1UsingMicrosoft.Data.Entity;2UsingSystem.Collections.Generic;34NamespaceEfgetstarted.consoleapp5{6PublicClassBloggingcontext:dbcontext7{8Public dbset<blog> Blogs {GetSet; }9Public dbset<post> Posts {GetSet; }1011ProtectedOverridevoidOnconfiguring (Dbcontextoptionsbuilder Optionsbuilder)12{13//Visual Studio 2015 | LocalDB 12 instances created with Visual StudioOptionsbuilder.usesqlserver (@"Server= (LocalDB) \mssqllocaldb;database=efgetstarted.consoleapp; Trusted_connection=true;");1516//Visual Studio 2013 | LocalDB 11 instances created with Visual Studio17//Optionsbuilder.usesqlserver (@ "server= (localdb) \v11.0;database=efgetstarted.consoleapp; Trusted_connection=true; ");1819//Visual Studio 2012 | Instances of SQL Express created using Visual Studio20//Optionsbuilder.usesqlserver (@ "SERVER=.\SQLEXPRESS;DATABASE=EFGETSTARTED.CONSOLEAPP; Trusted_connection=true; ");21st}2223ProtectedOverridevoidOnmodelcreating (ModelBuilder ModelBuilder)24{25//Configure Blog.url to RequiredModelbuilder.entity<blog>()27. Property (b =B.url)28. Required ();29}30}//Blog31PublicClassBlog32{33Publicint BlogId {GetSet; }34PublicString Url {GetSet; }3536Public list<post> Posts {GetSet; }37}38//Article39PublicClassPost40{41Publicint PostID {GetSet; }42PublicString Title {Getset43 public string Content {get; set44 45 public int BlogId {get; set46 public Blog Blog {get ; set47 }48}     

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;

1UsingSystem;23NamespaceEfgetstarted.consoleapp4{5ClassProgram6{7Staticvoid Main (String[] args)8{9using (var db =NewBloggingcontext ())10{One db. Blogs.add (New Blog {URL ="Http://blogs.msdn.com/adonet"});12var count =Db. SaveChanges ();Console.WriteLine ("{0} Records saved to database", count);1415Console.WriteLine ();Console.WriteLine ("All Blogs in database:");  (var blog in  db.) Blogs) {Console.WriteLine (" -{0}", blog. URL); } +}             

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?

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

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.