Java Attack c#--Application Development LINQ and EF

Source: Internet
Author: User
Tags connectionstrings

This chapter is a brief statement

In the previous chapter, the author has explained several knowledge points used in the WinForm development process. The author can take this as the beginning to study. In this chapter, we are talking about a point of knowledge related to ORM thought. Before we talk, let's think about the hibernate knowledge point of Java. Hibernate is also an ORM framework. Remember that there is a name hql in Hibernate. First of all, regardless of hql good and bad. The main thing is to understand what HQL's eyes are. The idea of ORM is to allow users to use object-oriented thinking when manipulating data, rather than two-dimensional data. So hql I think is an object-oriented thinking of SQL statements. So why do I have to talk about HQL? In fact, I think LINQ is a bit like him. If the project architecture is three tiers, it means that the business layer's developers are not looking at the two-dimensional data. Even SQL statements are manipulated in object-oriented thought form. and the EF (Entity Framework) can be said to be hibernate. That is, a data source that can be understood as LINQ. But HQL to be able to have effect on hibernate. LINQ can be used without EF.

LINQ syntax

. NET the classification of LINQ knowledge makes the writer feel powerless sometimes. Why is it? At the earliest, I thought that LINQ knowledge points were divided into three chunks. LINQ to SQL, LINQ to Entity, LINQ to Database, respectively. With the increase in LINQ usage, there are also LINQ to Xml, LINQ to Excel, and so on. I wonder if the reader can see the doorway. Can say. NET in the design of LINQ, there should be enough to think about the future expansion of the problem. Of course this is not the goal of this chapter. The most common use of the author in the development process is LINQ to SQL and LINQ to Entity. There's another one called LINQ to Object. For LINQ to Object, the author has always thought of LINQ to Entity. The author means that their knowledge should be put in one piece. All right. First, I'll talk about LINQ to SQL.

For LINQ to SQL, anyone who learns SQL syntax doesn't have to worry about getting started easily. Remember when I study, a look I go to the hql of another form? Of course hql is not LINQ or learning. It's no use talking so much. It is best to use a few.

First, build EF environment. build a project first, and then get the corresponding EF DLL through NuGet. For what NuGet is. I believe that people who have read the Java attack on c#--project development environment should be able to understand. Select "Reference" right click to manage NuGet packages.

Believe to see the above picture, we have found the entityframework. Click on "Install" to do it. This time the project will be more than one called Packages.config file. This records the currently installed DLL information. At the same time the physical directory will have more than one folder packages to exist these DLLs.

We see references inside the reference DLL for EF. This time we can do the EF thing.

Second, create a new EF context . EF has a very important class. Can be said to be the core point of learning EF. This class is DbContext. The author of a new class called Aomicontext inherit him. As follows

public class aomicontext:dbcontext{}

The DbContext class has several constructors. I am here to talk about a common bar. As follows

Public DbContext (string nameorconnectionstring);

It's just a constructor. A configuration name that means a connection string or a connection character for a configuration file. Remember the app. config you said in the previous section. Nothing wrong is to use him. Take a look at what I wrote.

<?xml version= "1.0" encoding= "Utf-8"?><configuration> <configSections> <!--for more information On Entity Framework configuration, visit http://go.microsoft.com/fwlink/? linkid=237468-<!--for more information on Entity Framework configuration, visit http://go.microsoft.com/fwli nk/? linkid=237468-<!--for more information on Entity Framework configuration, visit http://go.microsoft.com/fwli nk/? linkid=237468-<!--for more information on Entity Framework configuration, visit http://go.microsoft.com/fwli nk/? 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= "Aomi" connectionstring= "Data source=.;i Nitial Catalog=ado; Persist Security info=true; User Id=sa; password=123 "ProvIdername= "System.Data.SqlClient"/> </connectionStrings> <entityFramework> <      Defaultconnectionfactory type= "System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework" >    <parameters> <parameter value= "v11.0"/> </parameters> </defaultConnectionFactory> <providers> <provider invariantname= "System.Data.SqlClient" type= "System.Data.Entity.SqlServer.SqlProvid Erservices, Entityframework.sqlserver "/> </providers> </entityFramework></configuration>

The connectionstrings part of the above is written by the author himself. Others are auto-generated. NET has a node that configures the connection string itself. We're just going to write our own connection on this node.

<add name= "Aomi" connectionstring= "Data source=.;i Nitial Catalog=ado; Persist Security info=true; User Id=sa; Password=123 "providername=" System.Data.SqlClient "/>

All right. The next step is to modify the Aomicontext class. Let him have sex with the configuration of the corresponding connection string. As follows

public class Aomicontext:dbcontext    {public        aomicontext ()            : Base ("Aomi")        {}    }

See the red part of the code. The Aomi is the value that corresponds to the name of the Add node configured above. This time EF will go to the config file itself to find it.

Third, establish the mapping of tables and classes.

Table for the corresponding database:

CREATE TABLE [dbo]. [Catalogs] (    [ID] [int] NOT NULL,    [catalogname] [nvarchar] () null,    [catalogcode] [nvarchar] () null, CONSTRAINT [PK _catalogs] PRIMARY KEY CLUSTERED (    [ID] ASC) with (pad_index  = off, statistics_norecompute  = off, ignore_dup_ KEY = OFF, allow_row_locks  = on, allow_page_locks  = on) on [PRIMARY]) on [PRIMARY]

Data for the corresponding database

INSERT [dbo]. [Catalogs] ([ID], [catalogname], [Catalogcode]) VALUES (1, n ' snacks ', n ' c0001 ') INSERT [dbo]. [Catalogs] ([ID], [catalogname], [Catalogcode]) VALUES (2, n ' computer ', n ' c0002 ')

The author constructs a class to correspond with the table inside the database. This time, remember that the attribute should be the same as the column name inside the table. The code is as follows

Using system;using system.collections.generic;using system.linq;using system.text;namespace LinqExample{public    Class catalogs    {public        int ID {set; get;}        public string CatalogName {set; get;}          public string Catalogcode {set; get;}}    }

With the corresponding class, not yet. We also need to revise the Aomicontext class. This way you can access the corresponding class object through the Aomicontext class. That is the data. As follows

    public class Aomicontext:dbcontext    {public        aomicontext ()            : Base ("Aomi")        {} public        idbset< Catalogs> catalogs {set; get;}    }

Iv. implementation of EF.

Class program    {        static void Main (string[] args)        {            using (aomicontext ac = new Aomicontext ())            { C13/>iqueryable<catalogs> queryable = from C in AC. Catalogs select C;                List<catalogs> cataloglist = queryable. ToList ();                foreach (catalogs catalog in cataloglist)                {                    Console.WriteLine (string. Format ("id:{0} Catalogname:{1}", Catalog.id, catalog. CatalogName));                }            }            Console.readkey ();        }    }

Execution Result:

From the example above we can see the use of the from C in AC. catalogs select C; To obtain the corresponding data. This is LINQ to SQL. The prospectus says he is an object-oriented SQL statement. The SQL statement starts with a select and the end is indeterminate. LINQ to SQL typically starts with a from and ends with a select. Indicates which data source to start with and how to return it at the end. But we can see his return is a iqueryable<t> type. The fact that at this time he did not go to the execution to get the data. Can be solved for him now just to assemble SQL statements. only to Queryable. ToList (); it's going to execute. Get data. In order to learn the convenience of the author and add a few key words to let everyone look.

using (aomicontext AC = new Aomicontext ())            {                iqueryable<catalogs> queryable = from C in AC. catalogs where c.catalogname.contains ("eat") by C.catalogcode Ascending select C;                List<catalogs> cataloglist = queryable. ToList ();                foreach (catalogs catalog in cataloglist)                {                    Console.WriteLine (string. Format ("id:{0} Catalogname:{1}", Catalog.id, catalog. CatalogName));                }            }

After reading LINQ to SQL, let me take a look at what is the LINQ to entity? But this is similar to the syntax of LINQ. It's just a different way of using and writing. Change the example above.

using (aomicontext AC = new Aomicontext ())            {                //iqueryable<catalogs> queryable = from C in AC. catalogs where c.catalogname.contains ("eat") by C.catalogcode Ascending select C;                iqueryable<catalogs> queryable = AC. Catalogs.where (t = t.catalogname.contains ("Eat")). (t = t.catalogcode). Select (c=> c);                List<catalogs> cataloglist = queryable. ToList ();                foreach (catalogs catalog in cataloglist)                {                    Console.WriteLine (string. Format ("id:{0} Catalogname:{1}", Catalog.id, catalog. CatalogName));                }            }

It seems that I do not have to say and understand. is to become the corresponding keyword method. Nothing wrong. That's it. At this point, I can assume that both LINQ to Entity and LINQ to SQL must have corresponding data sources. This is where EF provides the data source for them. Both of them correspond to return iqueryable<t> types. Just LINQ to Entity is the method used. LINQ to SQL is more like SQL statements.

All right. Let's take a look at LINQ to object. Let's just say--either LINQ to SQL or LINQ to entity, both of them are inseparable from LINQ to object. LINQ to object is designed to handle in-memory data. We can see that there is a queryable in the example above. ToList (). If the author says ToList () is a LINQ to object will someone squirt me. Why does the author say that he is a LINQ to object? The main is ToList () is statically extended for ienumerable<t>. Ienumerable<t> are generally used for arrays and collections. In-memory. And the above is dedicated to the iqueryable<t> type. All right. If you really think the author is wrong, that is not to divide. All for LINQ syntax. LINQ also provides some of the more commonly used methods.

First: Returns the data. There is no data on the birth anomaly. You can also pass in the condition of the first data as a parameter. such as Queryable. First (t = T.catalogname.contains ("eat"));.

FirstOrDefault: The same child returns the first data, without data, and returns NULL. You can also pass in the condition of the first data as a parameter.

Last: The same way to get the final method. Use the same way.

LastOrDefault: The same way. It's like a firstordefault usage.

Skip: Given a number, the number is not taken out before it is taken out. It is generally used with the Take method to make paging functions.

Take: Indicates the quantity to be returned. You can understand the top keyword in the SQL statement.

Let me give you a list of LINQ to object.

list<string> src = new list<string> (); src. ADD ("A1"); Src. ADD ("B2"); src. ADD ("C4"); src. Add ("D5"); string value = src. First (t = T.startswith ("a")); Console.WriteLine (value);

Note: The author is such a sub-division. The general static extension Iqueryable<tsource> method belongs to the LINQ to entity. The static extension, ienumerable<tsource>, is LINQ to object. Two people are alike. Only LINQ to entity must have a data source. LINQ to object is typically processed in-memory data.

Entity Framework

The Entity framework is one of the ORM frameworks. So the ORM framework must have something he has more. To learn the Entity Framework, you must know what knowledge he has. The Entity framework is divided into code first, model first, and database first, depending on the development model. Let the author use the point of the earth to say it.

Code First mode: It is to generate the corresponding database and table by writing codes.

Model First mode: It's actually a bit like code first. It's just that he used it. NET is a file called XXX.EDMX to operate. Through him to generate the corresponding database and table.

Database First mode: It's the opposite of the previous two. First build the database and the table in the class that generated the pair. That is the code.

We are now going to learn the entity Framework. The author's personal opinion readers should choose Code First mode to learn. Why. Both the model first mode and the database first mode are mostly software tools that help you generate the corresponding code. So a lot of things we don't see at all. The code first mode is for developers to write hand-in-hand. I remember when I was using hibernate. Did not say only do one side of the thing. It is usually after the database table has been built. or write the corresponding mapping configuration file (Xxx.hbm.xml). Write a code generator on your own. The Entity framework intent is to help developers do off-side work. But this is also the author does not like. Because of this, there is a more knowledge point in the Entity Framework that is data migration. We all know in the process of development. may be because the table was not designed well. Suddenly find that you need to add a field. At such a time, the Entity Framework will do a lot of things. Let's say we're using code first. We add a property to the class in the code. At this point the Entity Framework is going to determine which attributes are old. which properties are modified. Which properties are newly added. The Entity Framework then updates the database. Is the data migration of the Entity Framework.

From the above explanation, we know that EF wants to help me do the other half of things, so you have to work on the database. Then there is the database setting, the table setting, and the data manipulation. The following are all speaking in code first mode.

1. EF settings for the database. when executing the code, EF will determine if there is a corresponding database. and operate on the database. is created or deleted in the creation. or update it? The main view is that you set the corresponding database operation mode. So EF provides us with three of them. Of course we can write one ourselves. Three classes are under the System.Data.Entity namespace. Createdatabaseifnotexists, Dropcreatedatabasealways, Dropcreatedatabaseifmodelchanges, respectively. Wenying good people can understand what's going on.

Public Aomicontext ()            : Base ("Aomi")        {            database.setinitializer<aomicontext> (new Createdatabaseifnotexists<aomicontext> ());        }

Note: The assignment of the Database.setinitializer method can be placed somewhere else. But be sure to execute EF before.

2. The EF sets the table. The big part of these settings is about how the relationships between tables and tables are reflected in the relationships between classes and classes. Here's an example of a simple mapping.

public class Aomicontext:dbcontext    {public        aomicontext ()            : Base ("Aomi")        {} public        idbset< Catalogs> catalogs {set; get;}        protected override void Onmodelcreating (Dbmodelbuilder modelBuilder)        {            base. Onmodelcreating (ModelBuilder);            MODELBUILDER.CONFIGURATIONS.ADD (New Catalogsmap ());        }    }

The following Catalogsmap class is equivalent to a mapping configuration file (Xxx.hbm.xml). These include a one-to-many, many-to-many relationships that are also configured here. One thing to note is the red code above. Which is to add the mapping relationship to the EF configuration.

public class catalogsmap:entitytypeconfiguration<catalogs>    {public        catalogsmap ()        } {this            . Haskey (t = t.id);            This. Property (t = t.catalogname). Hascolumnname ("CatalogName");            This. Property (t = T.catalogcode). Hascolumnname ("Catalogcode");        }    }

3, the operation of the data . The operation of the data is generally deleted and modified.

Increase:

using (aomicontext AC = new Aomicontext ()) {      Catalogs catalogs = new catalogs ();      Catalogs.id = 6;      Catalogs. CatalogName = "commodity";      Catalogs. Catalogcode = "s0001";      Ac. Catalogs.add (catalogs);                      Ac. SaveChanges ();}

In fact the code of the polygon is no problem. But there is a mistake when it comes to execution. Why is it? I'm not sure what the reason is. No problem finding. But the increase will be problematic. Let me have a look at the anomaly. Here the author only copies part of it.

       InnerException:System.Data.SqlClient.SqlException            _hresult=-2146232060            _message= cannot insert value NULL into column ' ID ', table ' Ado.dbo.Catalogs '; column does not allow Null values. INSERT failed. Statement has been terminated.            hresult=-2146232060            Istransient=false            message= cannot insert a value of NULL into the column ' ID ', table ' Ado.dbo.Catalogs '; the column does not allow null values. INSERT failed. Statement has been terminated.            source=.net SqlClient Data Provider            errorcode=-2146232060            _donotreconnect=false

He said my ID didn't set a value, but I set it up. I think you will certainly think that there is no identity set. That is, automatic growth. It's not like that. I did not want to automatically grow AH. So why is it wrong? The fact that the author is in such a perspective to think. Will the EF assume that the ID is automatically growing by default. Because the ID is of type int. Is the primary key again. So I added a piece of code to the mapping configuration. As follows

public class catalogsmap:entitytypeconfiguration<catalogs>    {public        catalogsmap ()        } {this            . Haskey (t = t.id);            This. Property (t = t.id). Hasdatabasegeneratedoption (databasegeneratedoption.none);            This. Property (t = t.catalogname). Hascolumnname ("CatalogName");            This. Property (t = T.catalogcode). Hascolumnname ("Catalogcode");        }    }

The red part is the added code. There will be no mistakes at this time. So what does this piece of code mean. is to tell EF that the ID here is just plain. No other settings.

Modify:

using (aomicontext AC = new Aomicontext ()) {     catalogs updatecatalogs = AC. Catalogs.firstordefault (t = t.id = = 4);     Updatecatalogs.catalogname = "paper type";                     Ac. SaveChanges ();}

Delete:

using (aomicontext AC = new Aomicontext ()) {catalogs deletecatalogs = AC. Catalogs.firstordefault (t = t.id = = 1); Ac. Catalogs.remove (deletecatalogs);                 Ac. SaveChanges ();}

When I do ef additions and deletions, my heart has been thinking about two questions?

The first: EF doesn't look like hibernate. There are additional methods and newer methods. He has only one concept that is that the data has not changed. Updates the database data according to the change data.

Second: Hibernate is dealing with objects. The three states of the object are used. These three states have different names in different books. I generally like to call them common-like, persistent, free-form. But if you put the knowledge of hibernate on the EF side, it's not that you can't. Just feel a little strange at this time. There is no such description on the EF side. But I still think it is necessary to use him on the EF side. Why is it? Let's take a look at the situation first. If we turn the above ID into an identity. That is automatic growth. There is no need to set this value at the time of the increase. What if we get the corresponding ID value after we increase the success? Are you getting it again? Obviously not. As follows.

Class program    {        static void Main (string[] args)        {            using (aomicontext ac = new Aomicontext ())            {                Catalogs catalogs = new catalogs ();                catalogs.id = 0;                Catalogs. CatalogName = "commodity";                Catalogs. Catalogcode = "s0001";                Ac. Catalogs.add (catalogs);                Ac. SaveChanges ();                Console.WriteLine ("ID:" + catalogs.id);            }            Console.readkey ();        }    }

The author removed all the above data. and change the column ID of the catalogs table to identity. That is automatic growth. Set the ID to 0 when creating a new Catalogs object. And then we're looking at whether the ID is still 0 after the increase in success. But remember to modify the mapping configuration inside the Catalogsmap class. Modify the following.

This. Property (t = t.id). Hasdatabasegeneratedoption (databasegeneratedoption.identity);

OK, let's see what the result value is. As follows. We saw that it was 7. Why not 0. The author's SQL Server identity is starting from 6. So this is 7. If you start. is 1. But it's not 0. Why? It's because the object has become a persistent shape.

Normal: It is normal to use the keyword new to create.

Persistent: After EF, for example, increase. This time the object is synchronized with the database.

Free form: The object after the EF is closed. But I think EF has no such state. Because hibernate has the ability to wake up.

This chapter summarizes

This chapter focuses on the points of Knowledge about LINQ and EF. Some of the introductory uses of LINQ and the basic knowledge points of EF. Of course, the author of the relationship between classes and classes of EF and data migration does not say. Readers are expected to see for themselves.

Java Attack c#--Application Development LINQ and EF

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.