LINQ to SQL establishes entity classes

Source: Internet
Author: User
Tags visual studio 2010

When using LINQ to SQL, you need to first establish a model for mapping database objects, that is, entity classes. At run time, LINQ to SQL generates SQL statements based on LINQ expressions or query operators that are sent to the database for operation. When the database returns, LINQ to SQL is responsible for converting the results into entity class objects.

There are many ways to create an entity class, such as the LINQ to SQL Designer, manual encoding Setup, XML file mapping, sqlmetal generation using command line tools, and so on. The most convenient of these is the LINQ to SQL Designer.

1. Building entity classes using the LINQ to SQL designer

In one example, add a "service-based database" Database1.mdf to the demo console program to create a tb_guestinfo table. The table is detailed as follows:

All of the following methods are used in this database.

Add a LINQ to SQL class to the project, with the default name DATACLASSES1.DBML, as follows:

Drag the Tb_guestinfo table to the interface and save.

OK, write the relevant code as follows, to implement additions and deletions to check:

Using system;using system.collections.generic;using system.linq;using system.text;namespace linq_to_sql Custom Database and entity class {/ <summary>///entity class Establishment ___1.vs entity class///</summary> class Program {static void Main (string[                        ] args) {//Dataclasses1datacontext DC = new Dataclasses1datacontext ();                                             1. Query iqueryable<tb_guestinfo> query = from P in Dc.tb_guestinfo            where p.name! = "XXX" select P;            foreach (var g in query) {Console.WriteLine ("{0} {1} {2} {3}", G.id,g.name,g.age, G.tel);            } Console.WriteLine ("-----------------");            Console.readkey (FALSE);             2. Add a record tb_guestinfo ginfo = new Tb_guestinfo () {Id = 9, Name = "m&m", age = +, Tel = "135****5555"};            Dc.tb_GuestInfo.InsertOnSubmit (Ginfo); dc. SubmitChanges ();            foreach (var g in query) {Console.WriteLine ("{0} {1} {2} {3}", G.id, G.name, G.age, G.tel);            } Console.WriteLine ("-----------------");            Console.readkey (FALSE); 3. remove var query_itemtodelete = from G in dc.tb_guestinfo where g.name = = "            M&m "Select G;            foreach (var g in Query_itemtodelete) {dc.tb_GuestInfo.DeleteOnSubmit (g); } DC.            SubmitChanges ();            foreach (var g in query) {Console.WriteLine ("{0} {1} {2} {3}", G.id, G.name, G.age, G.tel);            } Console.WriteLine ("-----------------");            Console.readkey (FALSE); 4. modify var query_itemtoupdate = from G in Dc.tb_guestinfo where G.name.cont Ains ("Debuglzq") select G;            foreach (var g in query_itemtoupdate) {g.name = G.name + "A"; } DC.            SubmitChanges ();            foreach (var g in query) {Console.WriteLine ("{0} {1} {2} {3}", G.id, G.name, G.age, G.tel);            } Console.WriteLine ("-----------------");        Console.readkey (FALSE); }    }}

The results of the program run as follows:

2. Create the entity class manually

Entity classes can be established in most cases through the LINQ to SQL Class Designer, but it is not difficult to build a simple entity class, and you can better learn the object model of LINQ to SQL. The database is still the previous sample database.

Add a class GuestInfoEntity.cs to the project as follows:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Data.Linq.Mapping; namespace datacontexdemo{    //    /<summary>///Manual entity classes    ///</summary> [Table (Name= tb_ Guestinfo ")]    class guestinfoentity    {        [Column (isprimarykey=true,dbtype=" Int not NULL IDENTITY ", Isdbgenerated=true,name= "id")] public        int Id {get; set;}        [Column (DbType = "nvarchar", name = "name")]        public string Name{get;set;}        [Column (DbType = "int", Name = "age")]        public int Age {get; set;}        [Column (DbType = "nvarchar", Name = "Tel")]        public string Tel {get; set;}}    }

Write the sample code and note the need to introduce System.Data.Linq.dll:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Data.Linq;// Follow namespace datacontexdemo{    class program    {        static void Main (string[] args)        {            //2. Creating entity classes manually            / /            //connection string            constring = @ "Data source=.\sqlexpress; Attachdbfilename=e:\visual Studio 2010\linq_to_sql\linq_to_sql Custom Database and entity class \database1.mdf;integrated Security=True; User instance=true ";            DataContext dc = new DataContext (constring);            table<guestinfoentity> TB = DC. Gettable<guestinfoentity> ();            var query = tb. AsEnumerable ();            foreach (var q in query)            {                Console.WriteLine ("{0} {1} {2} {3}", Q.id,q.name,q.age,q.tel);            }            Console.readkey ();}}}    

The program runs as follows:

3. Creating an entity class using an XML mapping file

The mapping of entity classes in addition to using inline attribute, you can also create an XML file that contains the mapping information. This file generates the System.Data.Linq.Mapping.XmlMappingSource object as a parameter to the DataContext object construction method.

This XML file has only one root node---database element, which is used to map information about the databases. The database element contains one or more table elements that are used to map information from a TABLE element, consisting of a type element and multiple column elements (or association elements). The type element is used to specify the entity class, which is used to specify column information, and the association element is used to map database relationships.

Add an XML file to the project with the default name Xmlfile1.xml, as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><database name= "Database1" xmlns= "http://schemas.microsoft.com/ linqtosql/mapping/2007 "><!--database name is optional, the namespace must be added--  <table name=" Tb_guestinfo "><!-- The name of the table in the database--    <type name= "Linqtosql establishes the entity class _xml. Guestinfoentity "><!--too bt, actually want full name; Guestinfoentity can't even do it.-          <column name= "id" member= "id" dbtype= "Int not NULL IDENTITY" isprimarykey= "true"/ >      <column name= "name" member= "name" dbtype= "nvarchar"/> <column name=      "age" member= "age" dbtype= "int"/>      <column name= "Tel" member= "tel" dbtype= "nvarchar"/>    </Type>  </ Table></database>

This XML file contains all of the mapping information for the class, and the following is a mapping class GuestInfoEntity.cs:

Using system;using system.collections.generic;using system.linq;using system.text;namespace linqtosql establishing entity classes _xml{   public  class guestinfoentity    {public               int ID {get; set;}                public string Name {get; set;}               public int Age {get; set;}                public string Tel {get; set;}}    }

Writing the sample code also requires the introduction of System.Data.Linq.dll:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Data.Linq;using System.data.linq.mapping;using System.io;//namespace Linqtosql establishing entity Class _xml{    class program    {        static void Main (string[] args)        {            string constring = @ "Data source=.\sqlexpress; Attachdbfilename=e:\visual Studio 2010\linq_to_sql\linq_to_sql Custom Database and entity class \database1.mdf;integrated Security=True; User instance=true ";            Xmlmappingsource map = Xmlmappingsource.fromxml (File.readalltext ("Xmlfile1.xml"));            DataContext dc = new DataContext (constring, map);            table<guestinfoentity> TB = DC. Gettable<guestinfoentity> ();            var query = tb. AsEnumerable ();            foreach (var g in query)            {                Console.WriteLine ("{0} {1} {2} {3}", G.id,g.name,g.age,g.tel);            }            Console.readkey ();}}}    

The program runs as follows:

Http://www.cnblogs.com/DebugLZQ/archive/2012/11/14/2770449.html

LINQ to SQL establishes entity classes

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.