EntityFramework 5.0 Codefirst Tutorial 01-Build your environment and get started quickly

Source: Internet
Author: User

----------------------------Directory------------------------------

EntityFramework 5.0 Codefirst Tutorial 01-Build your environment and get started quickly

----------------------------Directory------------------------------

Online about EntityFramework 5.0 tutorial a lot, but most of the code is not clear, some even copy, code loss and other issues, I recently also have a project is used EntityFramework 5.0 and is the use of code first way, In view of this on Google to find a foreign people write code first ebook, English version, with the electronic dictionary to look down, feel good, write very clear and organized, so share to everyone.

The first is the download of e-books, if you want to see only e-book friends, you can download it directly, no longer read down.
, Baidu Network disk: Http://pan.baidu.com/s/1bne2QsRThis tutorial is only suitable for use, so at the beginning of the code, if you want to master a variety of theoretical friends, may not be suitable to continue reading, if you want to quickly use the EntityFramework 5.0 codefirst, you can read down to create a. NET 4.5 Console application, I use the VS 2013 recommended that the reader also use this IDE is a console application, the following referenceEntityFramework.dllFirst we create a class of person, with only the surname FirstName and the name LastName and the primary key ID (PERSONID)  Everything starts from the simple, not like other tutorials, examples are very complex, examples should be to grasp the core, excluding other and subject matterbamn.cnThe entire class is as follows:
 Public class person    {        publicintgetset;}          Public string Get Set ; }          Public string Get Set ; }    }

We'll create another Personcontext context class that needs to inheritDbContext
 Public class Personcontext:dbcontext    {        public  personcontext ()            base("name=dblink"          {        }        publicgetset;}    }

The careful classmate may see behind the construction methodbase("Name=dblink") Here the Dblink is the database connection name, look at the following configuration file is clear Then there is the connection to the database, add the link string in the config file App. config <?xml version= "1.0" encoding= "Utf-8"?><configuration> <connectionStrings> <add name= " Dblink"connectionstring= "Data source=.\mssqlserver2008;initial Catalog=efdemo; User Id=sa; password=123321; "providername= "System.Data.SqlClient"/></connectionStrings>    <startup>         <supportedruntime version= "v4.0" sku= ". netframework,version=v4.5 "/>    </startup></configuration>      Here we operate on the database, the first is to create a database, to create a database trial EF just need a code to do, EF will help us to the database and data table created we add the following code in the main method of Program.cs  
class program    {        staticvoid Main (string[] args)        {            using (  varNew  personcontext ())            {                // If the database is not present, create                 BOOL res = personContext.Database.CreateIfNotExists ();            }            Console.readkey ();        }    }

we looked up the database and found that the database was created automatically and there are tables, see: Here's one thing to note:When the entity person is created, a primary key is required, and the primary key must be the class name +id like herePersonId , if you change into something else, like, you change the class toPersonmodel but ID or PersonId so long will report the following error, here to pay attention to the place, there is the ID can be written here is no problem, this should be Microsoft's EF framework is a conventional place.One or more validation errors were detected during model generation:\tsystem.data.entity.edm.edmentitytype:: EntityType ' Personmodel ' has no key defined. Define the key for this EntityType.\tsystem.data.entity.edm.edmentityset:entitytype:entityset ' People ' is based on type ' Personmodel ' This has no keys Defined.Let's add a piece of data to the table by adding the following code to the Main method
// adding data to the database var New person{    "John",    "Doe" };p ersonContext.People.Add (person);p ersoncontext.savechanges ();

Query table discovery records have been added in the execution of all operations are basically implemented through this context, such as adding records, only need to add an entity to go in and then savechanges this method to execute, EF will save the data into the table. Let's get the data from the table again.
// Get Data var savedpeople = personcontext.people; foreach (var in savedpeople) {    Console.WriteLine ("lastName:{0},first name:{1} , id {2}",    p.lastname, P.firstname, P.personid);}

Getting the data is also very simple, here is to get all the records, and then traverse to get the data, it is very convenient when we execute several times just the code, EF will add more than one record, and the ID is not the same, the ID primary key is self-growing all the code is as follows:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceconsoleapplication2{classProgram {Static voidMain (string[] args) {            using(varPersoncontext =NewPersoncontext ()) {                //If the database does not exist, create                BOOLres =personContext.Database.CreateIfNotExists (); //adding data to the database                varperson =NewPerson {FirstName="John", LastName="Doe"                };                PERSONCONTEXT.PEOPLE.ADD (person);                Personcontext.savechanges (); //Get Data                varSavedpeople =personcontext.people; foreach(varPinchsavedpeople) {Console.WriteLine ("Last name:{0},first name:{1},id {2}", P.lastname, P.firstname, P.personid);        }} console.readkey (); }    }}
Code structure: This set Source: HTTP://PAN.BAIDU.COM/S/12LWO2

EntityFramework 5.0 Codefirst Tutorial 01-Build your environment and get started quickly

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.