• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Leonny's Blog
走自己的路
博客园    首页    新随笔    联系   管理    订阅  订阅

關於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);
    }
}
posted @ 2007-09-22 18:09  Leonny  阅读(1210)  评论(2)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3