EF three Programming details tutorial (C#+EF) Code First

Source: Internet
Author: User
Code A

The code first mode, which we call "coding priority" mode, is a new join function from EF4.1. When using the code-S model for EF development, developers only need to write the corresponding data classes (in fact, the implementation of the domain model), and then automatically generate the database. The advantage of this design is that we can do all the data operations on the conceptual model without having to store relationships with the data, making it more natural for us to adopt object-oriented approaches to data-oriented application development.

In some ways, the distinction between "code first" and "model first" is not too obvious, except that it does not rely on the Entity Data Model Designer, but instead designs the entity model directly by encoding (data Class) (which is why "code first" is called "code Only "reason). However, there are differences in the processing of the EF, for example, we no longer need the EDM file with code A, and all mappings are mapped and configured through the data annotation and the fluent APIs. It is also important to note that "Code number one" does not necessarily mean that the model must be defined through a data class, but it can actually generate data classes from an existing database.

So let's take a look at how the traditional code first is used.

First create a console application, then add two classes "order" and "OrderDetail", we can see that these two classes are just simple C # objects (Poco,plain old C # object) These two classes have nothing to do with EF. It should be noted that these two classes have two navigation properties "Order.orderdetails" and "Orderdetail.order":

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;

Namespace Demoef
{
    class order
    {public
        int Id {get; set;}
        public string Customer {get; set;}
        Public System.DateTime OrderDate {get; set;}

        Public virtual list<orderdetail> OrderDetails {get; set;}}}
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;

Namespace Demoef
{
    class OrderDetail
    {public
        int Id {get; set;}
        public string Product {get; set;}
        public string UnitPrice {get; set;}
        public int OrderId {get; set;}

        Public virtual order: {get; set;}}}

With these two classes, let's define a database context, and with it we can do a System.Data.Entity.DbContext of the data, which must be inherited from the class to give it the ability to manipulate data. So next we need to install the EntityFramework package for this application because so far we have not introduced anything related to the EF framework, we need to introduce an EF-related assembly. But we have a better choice, and that's nuget. On-line installation via NuGet: In the project, select "Manage NuGet Packages ..."; select online; then select "EntityFramework"; then click Install.

Database context Action class:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;

Namespace Demoef
{
    class program
    {
        static void Main (string[] args)
        {
            using (var ctx = new OrderContext ())
            {

                var o = New Order ();
                O.orderdate = DateTime.Now;
                CTx. Orders.add (o);
                CTx. SaveChanges ();

                var query = from order in CTX. Orders
                            Select order;
                foreach (var q in query)
                {
                    Console.WriteLine ("Orderid:{0},orderdate:{1}", Q.id, q.orderdate);
                }

                Console.read ();}}}

Run Result:

If it is the first time you use the EF Code One, you will have a question, we do not have any database configuration, add a data through the query is actually saved, then our data in the end. In fact, if the user does not make the database configuration EF uses the ". \SQLExpress" database instance by default, if you do not install ". \SQLExpress", the default is to use LocalDB, for specific details on LOCALDB, see: SQL Server 2012 Express LocalDB. Here we can find the database automatically created by the system:

But most of the time we want to control the database, for example, I want him to save it on my machine's ". \sql2008" instance, at which point we need to configure a database connection string in the configuration file app.config and then specify the connection name in our database context.

App.config configuration file:

<?xml version= "1.0" encoding= "Utf-8"?> <configuration> <configSections> <!--for more Informati On Entity Framework configuration, visit http://go.microsoft.com/fwlink/? linkid=237468--> <section name= "EntityFramework" type= " System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, version=6.0.0.0, Culture=neutral,
    publickeytoken=b77a5c561934e089 "requirepermission=" false "/> </configSections> <connectionStrings> <add name= "Codefirstdb" connectionstring= "Data source=lenovo\sqlexpress;database=codefirstdb; Uid=sa; Pwd=sql; "Providername=" System.Data.SqlClient "></add> </connectionStrings> <startup> <sup Portedruntime version= "v4.0" sku= ". netframework,version=v4.5 "/> </startup> <entityFramework> <defaultconnectionfactory type=" Syste M.data.entity.infrastructure.sqlconnectionfactory, entityframework "/> <providers> <provider INvariantname= "System.Data.SqlClient" type= "System.Data.Entity.SqlServer.SqlProviderServices, Entityframework.sqlserver "/> </providers> </entityFramework> </configuration>

OrderContext class, the constructor has one more connection name parameter:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using System.Data.Entity;

Namespace Demoef
{
    class Ordercontext:dbcontext
    {public
        OrderContext (string connectionname)
            : Base (ConnectionName)
        {
        } public
        dbset<order> Orders
        {get
            ;
            Set;
        }

        Public dbset<orderdetail> OrderDetails
        {get
            ;
            Set;}}}

When used, the database connection string name of the incoming configuration:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;

Namespace Demoef
{
    class program
    {
        static void Main (string[] args)
        {
            using (var ctx = new OrderContext ("Codefirstdb"))
            {

                var o = New Order ();
                O.orderdate = DateTime.Now;
                CTx. Orders.add (o);
                CTx. SaveChanges ();

                var query = from order in CTX. Orders
                            Select order;
                foreach (var q in query)
                {
                    Console.WriteLine ("Orderid:{0},orderdate:{1}", Q.id, q.orderdate);
                }

                Console.read ();}}}

After execution, you will find a "codefirstdb" database on the ". \SQLExpress" instance (note that there is a system table in addition to the two entity tables we created dbo._migrationhistory it records the definition of the model. In future articles I will focus on explaining this table):

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.