关于Web Service 中使用NHibernate时无法序列化IList的问题

用NHibernate进行数据库的ORM操作, 很多清况下都免不了要生成像IList这种泛型接口的对象集合.
但是如果再用到Web Service来进行这种对象的传输的话, 就会报错.
原因是IList为接口类型, 不能被序列化.
今天刚好在项目中碰到这种问题. google了半天, 未果!
没办法, 还得自己想办法.
最后通过以下方法解

//要用到的主要类
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;

//Web Service 方法, 假定
[WebMethod(Description = "Input the order No. to get the order's information.")]
public byte[] GetOrderByNo(string orderNo)
{
    BinaryFormatter formatter 
= new BinaryFormatter();
    List
<string> orderList = new List<string>();
    OrderNoBLL onBll 
= new OrderNoBLL();    //以下是从NHibernate中
    OrderBLL bll = new OrderBLL();            //获得对象的方法,具体的操作
    OrderNo on = onBll.GetByNo(orderNo);    //
    byte[] bs;
    
if (on != null)
    {
        MemoryStream ms 
= new MemoryStream();    //这里是关键
        
//on.Order是一个Order对象, 其中有一个Items的IList<OrderItem>属性
        formatter.Serialize(ms, on.Order);        //这里可以进行序列化, ^_^
        bs = ms.ToArray();
    }
    
else
    {
        bs 
= new byte[0];
    }
    
return bs;
}

下面的代码是Client端的接收和反序列化的代码:

protected void btn_Click(object sender, EventArgs e)
{
    localhost.WebService service 
= new localhost.WebService();
    
byte[] bs = service.GetOrderByNo(no.Text);    //从这里取得传回的二进制数组
    Entity.Order order = null;
    
try
    {
        MemoryStream ms 
= new MemoryStream(bs);    //这里是关键
        BinaryFormatter formatter = new BinaryFormatter();
        order 
= (Entity.Order)formatter.Deserialize(ms);    //再反序列化
        noLb.Text = order.ID;
    }
    
catch(Exception ex)
    {
        Response.Write(ex.Message);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章