Silverlight 2 (beta1) data manipulation (5)--Using LINQ to SQL for data crud Operations (top)

Source: Internet
Author: User
Tags serialization management studio silverlight

Introduction

Silverlight 2 supports new features such as JSON, Web Service, WCF, and sockets for data crud operations, a series that uses examples in conjunction with a database step-by-step description to learn about Silverlight 2 Beta 1 in the database of CRUD operations in the actual combat capabilities.

This article describes how to use LINQ to SQL for data crud operations in Silverlight 2 Beta 1. I have roughly divided this example into 3 layers.

Here are a few more words: Microsoft released is Silverlight 2 beta1 is not Silverlight 2.0, also not Silverlight 2.0 Beta 1, but now a lot of blog, News put Silverlight 2 Beta1 Wrong understanding of Silverlight 2.0 or Silverlight 2.0 Beta 1, here specifically, the real Silverlight 2 beta1 is not Silverlight 2.0, nor is Silverlight Beta 1 for 2.0! I hope beginners do not misunderstand this "concept".

Software Requirements
    • Silverlight 2 (Beta1)
    • Visual Studio 2008
    • SQL 2005 Express with Management Studio
Database implementation

In this article, we design a science and technology achievement table. Contains the following fields: Result number, name, type, completion time, results, responsible person, Achievement Award unit. For demonstration purposes, the data type is not specifically defined. As shown below:

The Data access layer implements

There are a number of techniques available at the data access layer, such as NHibernate, Nettiers, LINQ to SQL, Entity Framework, Astoria (ADO. NET Data Services). VS2008 provides us with a visual editing environment for the or designer (LINQ to SQL Technology) to map the data tables. First create a Silverlight project in Visual Studio 2008 and then add LINQ to SQL. Here's a step-by-step explanation:

First step: Create a new Silverlight project, which I named: Yjinglee.academe. and select ASP. NET Web site to host the Silverlight application.

Step two: Add LINQ to SQL in your Web project.

In this step, vs will prompt you to create a new App_Code directory and place the academe.dbml file under this folder

Step three: Map tables. We drag the database table to the or designer,

Step three: Define the data contract. This is only required in the or designer to modify the serialization property to unidirectional.

In addition, in order to implement the update operation method, we modify the property of each field here to Updatecheck=updatecheck.never. At this point in the CS file, the designer automatically generates some code. To illustrate the problem here I post the relevant incomplete code.

[Table(name="dbo. Product ")][DataContract()]Public Partial classProduct:inotifypropertychanging,INotifyPropertyChanged{ PublicProduct () { This.    Initialize (); }        [Column(storage="_productid", autosync=AutoSync. OnInsert, dbtype="Int not NULL IDENTITY", isprimarykey=true, isdbgenerated=true, updatecheck=UpdateCheck. Never)] [DataMember(order=1)]public intproductid{} [Column(storage="_productname", dbtype="VarChar", updatecheck=UpdateCheck. Never)] [DataMember(order=2)]Public Stringproductname{} [Column(storage="_producttype", dbtype="VarChar", updatecheck=UpdateCheck. Never)] [DataMember(order=3)]Public Stringproducttype{} [Column(storage="_completetime", dbtype="VarChar", updatecheck=UpdateCheck. Never)] [DataMember(order=4)]Public Stringcompletetime{} [Column(storage="_productimage", dbtype="VarChar", updatecheck=UpdateCheck. Never)] [DataMember(order=5)]Public Stringproductimage{} [Column(storage="_principal", dbtype="VarChar", updatecheck=UpdateCheck. Never)] [DataMember(order=6)]Public Stringprincipal{} [Column(storage="_awardunit", dbtype="VarChar", updatecheck=UpdateCheck. Never)] [DataMember(order=7)]Public Stringawardunit{}private voidInitialize () {oncreated (); }        [ondeserializing()] [System.ComponentModel.Editorbrowsableattribute(editorbrowsablestate. Never)]Public voidOnDeserializing (StreamingContextContext) { This.    Initialize (); }}

Here, we can see that vs automatically adds the DataContract property to the table (mapped here as a class), adds the DataMember attribute to the serialized member, and sets the Order property of the DataMember attribute to provide a sequence of serialization for WCF. In addition, a serialized ondeserializing event is added, which occurs before deserialization to initialize a class member.

WEB Service Layer Implementation

The service layer is the Silverlight client and the Web server to provide a channel, the official recommended use of WCF to read, of course, ASMX can also. I think Microsoft may be designing a silverlight-enabled WCF service for Silverlight in the near future, but now it can be accessed using a WCF service. When using this, be sure to change the wshttpbinding to BasicHttpBinding in the Web. config file.

First step: Add a WCF Service

Step Two: Define the service contract. We define the service contract for the additions and deletions method provided by the WCF service.

[ServiceContract]Public InterfaceIacademeservice{    [OperationContract]List<Product> getallproducts (); [OperationContract]ProductSaveproduct (Productproduct); [OperationContract]voidDeleteproduct (Productproduct);}

The third step: realize the service: for adding and deleting the method of concrete implementation.

Here, to provide a little tip, click on the small arrow under Iacademeservice, choose the implementation interface, VS automatically generated for us the above definition of the method is not implemented.

We then complete these methods: where the Saveproduct method is used to update and insert data, and LINQ to SQL statements are used here.

Public classAcademeservice:Iacademeservice{ PublicList<Product> getallproducts () {Academedatacontextdb =NewAcademedatacontext();varProducts = fromPinchDb. ProductsSelectPreturnProducts. tolist<Product> (); } PublicProductSaveproduct (ProductProduct) {Academedatacontextdb =NewAcademedatacontext();if(Product. ProductID > 0) {//update recordDb. Products.attach (Product,true); }Else{//Insert recordDb.        Products.insertonsubmit (product); } db. SubmitChanges ();returnProduct }Public voidDeleteproduct (ProductProduct) {Academedatacontextdb =NewAcademedatacontext(); Db. Products.attach (Product,true); Db.        Products.deleteonsubmit (product); Db.    SubmitChanges (); }}

Fourth step: Configure the Web.cofig file. Just change the wshttpbinding to BasicHttpBinding.

        <servicebehaviors> <Behaviorname="Academeservicebehavior"> <Servicemetadatahttpgetenabled="true"/> <ServicedebugIncludeexceptiondetailinfaults="false"/> </Behavior> </servicebehaviors> </Behaviors> <Services> <Servicebehaviorconfiguration="Academeservicebehavior"name="Academeservice"> <EndpointAddress=""binding="BasicHttpBinding"Contract="Iacademeservice"> <Identity> <DNSvalue="localhost"/> </Identity> </Endpoint> <EndpointAddress="Mex"binding="mexhttpbinding"Contract="IMetadataExchange"/> </Service> </Services></System.ServiceModel>

Fifth step: Set the port number of the Web application. Set the port number of the device to 52600, and see if the service is working in the browser.

To do this, compile the Web project, we've done everything, and the next step is to invoke the service in Silverlight.

Copyright NOTICE: This article for Bo Master http://www.zuiniusn.com original article, without Bo Master permission not reproduced.

Silverlight 2 (beta1) data manipulation (5)--Using LINQ to SQL for data crud Operations (top)

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.