LinQ,WCF,ExtJs之”初吻“

昨天花了一天的时间尝试了.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
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5using ExtjsNorthwind.Model;
 6using System.ServiceModel;
 7using System.ServiceModel.Web;
 8namespace 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:代码下载

posted @ 2008-01-06 14:09  Awen  阅读(1209)  评论(1编辑  收藏  举报