LinQ,WCF,ExtJs之”初吻“

本文介绍了作者使用.NET Framework 3.5进行开发的体验,包括利用LinQ编写数据访问层代码的感受,遇到的问题及解决办法,并详细展示了如何使用WCF返回JSON格式的数据。
昨天花了一天的时间尝试了.net framework3.5的特性!用LinQ写数据访问层的代码,感觉很清爽,而且也非常灵活!WCF就比较有点“重量级”了,呵呵,昨晚闹了一个晚上,竟是一个返回类型不支持,弄了一整晚!至于ExtJs,这个可是这次尝试的导火线啊,本来想用3.5的一个JSON序列化类来转换与ExtJs交换数据,于是用到 System.Web.Script.Serialization;命名空间下的 JavascriptSerializer类 ,可正式版中,编译时竟说该方法过时 ,设置断点调试,返回值为null,然后查了一下资料,又有一个 System.Runtime.Serialization下的DataContractJsonSerializer类,但是这个类好像在正式版中是不存在的 。然后看到了 小庄的WCF和ExtJS系列,于是就用WCf中的特性来返回JSON格式数据!顺便了解一下WCF,^_^!
感觉WCF给分布式开发带来的方便不是一般的,效率好像也还不错(编译好第1+n次的访问速度总是比第n次快【本机上】),
然后用LinQ写了个简单的DataAccessLayer,先是定义接口,我们叫它做契约!它加了WCF的特性,继承自它的服务会自动继承其特性,数据库用Northwind
 1 using  System;
 2 using  System.Collections.Generic;
 3 using  System.Linq;
 4 using  System.Text;
 5 using  ExtjsNorthwind.Model;
 6 using  System.ServiceModel;
 7 using  System.ServiceModel.Web;
 8 namespace  ExtjsNorthwind.ServiceContract
 9 {
10    [ServiceContract]
11    
12   public interface IProductService
13    {
14       [OperationContract]
15       [WebInvoke(BodyStyle=WebMessageBodyStyle.Bare,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json,UriTemplate="/Get")]
16        List<Product> GetProductById(int id);
17       [OperationContract]
18       [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetAll")]
19       List<Product> GetProducts();
20    }

21}

接下来实现这个契约
using  System;
using  System.Linq;
using  System.Collections.Generic;
using  System.Runtime.Serialization;
using  System.ServiceModel;
using  System.ServiceModel.Activation;
using  System.ServiceModel.Web;
using  ExtjsNorthwind.Model;

namespace  ExtjsNorthwind.ServiceContract
{

    [AspNetCompatibilityRequirements(RequirementsMode 
= AspNetCompatibilityRequirementsMode.Allowed)]
    
public class ProductService:IProductService
    
{
       
        
public List<ExtjsNorthwind.Model.Product> GetProductById(int id)
        
{
            
using (NorthwindDataContext db=new NorthwindDataContext())
            
{
                
return (from p in db.Products where (p.ProductID == id) select p).ToList();

            }

        }

       
        
public List<ExtjsNorthwind.Model.Product> GetProducts()
        
{
            
using (NorthwindDataContext db = new NorthwindDataContext())
            
{
               
return (from p in db.Products select p).ToList();

            }

        }

    }

}
注意这里返回类型不能为IList<>类型!否则会出错,不能序列化!
此外测试了一个简单的一对多的序列化
写了一个Student类代码很简单,就不贴了,其中有一个List<Product>类型得ProductList属性,返回这个学生买的产品资料!加上[DataMember]特性!OK: 代码下载

转载于:https://www.cnblogs.com/Ablog-sunny/archive/2008/01/06/1027799.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值