Many tutorials on the Internet are tied to mvc3. If mvc3 is left blank, how can we use it?
Create a console applicationProgramWe name it efcodefirst-books.
Step 2: add an entityframework reference.
Don't say that you are not using nuget again. If not, ask du Niang. Enter install-package entityframework in the nuget console. nuget will reference the latest EF version. The current version is 4.3.
Step 3: add an object class.
I created a new models folder and added the book class to it. The class definition is as follows:
Using System; Using System. Collections. Generic; Using System. LINQ; Using System. Web; Namespace Efcodefirst_books.models { Public Class Book { Public Int Bookid { Get ; Set ;} Public String Bookname { Get ; Set ;} Public String Author { Get ; Set ;} Public String Publisher { Get ; Set ;} Public Decimal Price { Get ; Set ;} Public String Remark { Get ; Set ;}}}
Because it is a test, I added only one class.
Step 4: add the dbcontext class.
UsingSystem;UsingSystem. Collections. Generic;UsingSystem. LINQ;UsingSystem. Web;UsingSystem. Data. entity;NamespaceEfcodefirst_books.models {Public ClassAppdbcontext: dbcontext {PublicDbset <book> books {Get;Set;}}}
Step 5: check your database connection
If sqlexpress is installed, EF automatically points the connection to sqlexpress, and you do not need to modify it here.
If you want to change to another location, you need to modify the database connection:
< Entityframework > < Defaultconnectionfactory Type = "System. Data. entity. Infrastructure. sqlconnectionfactory, entityframework" > < Parameters > < Parameter Value = "Data Source =.; initial catalog = efcodefirst_books; Integrated Security = true" /> </ Parameters > </ Defaultconnectionfactory > </ Entityframework >
Here I am pointing to the local database, using integrated security verification.
Step 6: Start crud operations
Using System; Using System. Collections. Generic; Using System. LINQ; Using System. text; Using Efcodefirst_books.models; Namespace Efcodefirst_books { Class Program { Static Void Main ( String [] ARGs) {book = New Book () {bookname = " C # Advanced Programming " , Price = 151.8 m , Publisher = " Tsinghua University Press " , Author = " Wrox " ,}; Appdbcontext dbcontext = New Appdbcontext (); dbcontext. Books. Add (book); dbcontext. savechanges (); VaR Booksquery = From B In Dbcontext. Books Select B; List <Book> bookslist = Booksquery. tolist (); book = Bookslist [0 ]; Book. Price = 203 m; dbcontext. savechanges (); dbcontext. Books. Remove (book );}}}