This article reads Code-first develoment with the Entity Framework for simple notes.
1. First we create a person class
Public class person { publicintgetset;} Public string Get Set ; } Public string Get Set ; } }
Then create the context class, which inherits from the DbContext class
Public class Context:dbcontext { publicbase("ConnectionString") { } Public Get Set ; } }
Note that base ("ConnectionString") needs to configure the link string, otherwise EF will use the default connection settings.
< connectionStrings > < name= "ConnectionString"ConnectionString= "Data source=192.168.0.14; Initial Catalog=efsample;user id=sa;password= "providerName=" System.Data.SqlClient " /></connectionStrings>
Using the code below, if the database does not exist, the data is created in the data
Static voidMain (string[] args) { using(varcontext=NewContext ()) { BOOLtemp=context. Database.createifnotexists (); if(temp) {Console.WriteLine ("Create success!"); } Else{Console.WriteLine ("creation failed!"); }} console.readkey (); }
After running this code you will find that you have created a database named "Efsample" in the database, which is the name of the database that you just set the connection string to in the configuration file.
2. Add a record to the database we created
classProgram {Static voidMain (string[] args) { using(varcontext=NewContext ()) { BOOLtemp=context. Database.createifnotexists (); varperson =NewPerson {FirstName="John", LastName="Doe" }; Context. People.add (person); Context. SaveChanges (); } console.readkey (); } }
Using this code will find that the people table is created in the database and adds a record that EF automatically determines whether there is a people table in the database (the table name is based on the public dbset<person> people {get) defined in the context class; Set } property name). We can also map the tables we've created, which we'll cover later. In this code you find that we do not assign a value to PersonID, and EF automatically sets the +id name to the table primary key.
Entity Framework Learning One: Creating a new database on a. NET class basis