The code first mode, which we call the "coding priority" mode, when you use the code in the development of EF, developers only need to write the corresponding data class (actually is the domain model implementation process), and then automatically generate the database. The advantage of this design is that we can do all the data operations against the conceptual model without having to relate the storage relationships of the data, so that we can use the object-oriented approach to the development of data-oriented applications more naturally. Here we are. Create a console application, create two classes of Orders.cs and OrdersDetail.cs
Public classOrders {[Key]//PRIMARY Key Public intId {Get;Set; } [Stringlength (Ten)]//length Public stringOrderscode {Get;Set; } Public intCustomerID {Get;Set; } PublicSystem.DateTime CreateDate {Get;Set; } Public VirtualList<ordersdetail> Ordersdetaillist {Get;Set; } } Public classOrdersdetail {[Key]//PRIMARY Key Public intId {Get;Set; } Public intProductID {Get;Set; } [Stringlength ( -)]//length Public stringProductName {Get;Set; } Public stringUnitPrice {Get;Set; } Public intOrderId {Get;Set; } Public VirtualOrders Orders {Get;Set; } }
Next, install EntityFramework through NuGet.
Then create the OrdersContext.cs
Public class Orderscontext:dbcontext { publicgetset;} Public Get Set ; } }
Client Calls
classProgram {Static voidMain (string[] args) { varD = DateTime.Now.Date.ToString ("yyyymm"); varOrd =NewOrders {Orderscode="100001", CustomerID=1, CreateDate=DateTime.Now}; using(varContext =NewOrderscontext ()) {context. Orders.add (ORD); Context. SaveChanges (); } Console.WriteLine ("OK"); Console.ReadLine (); } }
If this is the first time you have a friend with EF Code, there will be doubt, we do not have any database configuration, add a piece of data through the query is actually saved, then where is our data exactly? In fact, if the user does not configure the database, EF will use the ". \SQLExpress" db instance by default. Below we use our own database and need to configure App. Config, which is the database connection: <connectionStrings> <add name= "Orderscontext" connectionstring= " Data source=.;D Atabase=ordersdb; Uid=sa; pwd=123456; "Providername=" System.Data.SqlClient "></add> </connectionStrings> Run program at times:
OK, finish, click Download Code.
03-code First