当前位置:首页 --> SQLCE --> 正文

如何在ASP.NET下使用SQLCE

2008-6-22 13:37:00 来源: 浏览次数: 评论数: 字号:[ ]
        在上一篇:SQLCE简介及资源 提到,SQL CE支持的平台有:desktop, Pocket PC, Smartphone 和 Tablet PC,但是在asp.net下面使用时,会提示:
       
        SQL Server Compact 不能用于 ASP.NET 开发。
 
       一开始也很奇怪为什么会有这样的限制,据google后的结果,其实CE一开始是没有这样的限制的,是因为CE支持Desktop后,IIS服务提供商警告MS如果不限制则改用xxxx。这样MS才后来加上的。
  那还能在ASP.NET下面应用SQL CE吗?答案是肯定的。
  那怎么应用呢?由于网上很多介绍CE的文章都是针对CTP版本介绍的,使用该方法对v3.5进行破解并没有起效。我们看下报错时的堆栈跟踪:
[NotSupportedException: SQL Server Compact 不能用于 ASP.NET 开发。]
   System.Data.SqlServerCe.SqlCeRestriction.CheckExplicitWebHosting() +108
   System.Data.SqlServerCe.SqlCeConnection..ctor() +16
   System.Data.SqlServerCe.SqlCeConnection..ctor(String connectionString) +12
   WebApplication1._Default.Page_Load(Object sender, EventArgs e) in E:\项目\WebApplication1\WebApplication1\Default.aspx.cs:24
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33
   System.Web.UI.Control.OnLoad(EventArgs e) +99
   System.Web.UI.Control.LoadRecursive() +47
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436
可以看到,在创建SqlCeConnection的时候会调用SqlServerCe.SqlCeRestriction.CheckExplicitWebHosting()方法,它的代码为:

public static void CheckExplicitWebHosting()

{

    if (!IsExplicitlyEnabled() && IsWebHosted())

    {

        throw new NotSupportedException(Res.GetString(CultureInfo.CurrentCulture, "SQLCE_WebHostingRestriction"));

    }

}
 
IsExplicitlyEnabled()方法:

private static bool IsExplicitlyEnabled()

{

    bool flag = false;

    object data = AppDomain.CurrentDomain.GetData("SQLServerCompactEditionUnderWebHosting");

    if ((data != null) && (data is bool))

    {

        flag = (bool)data;

    }

    return flag;

}
        到这时,破解的方法就已经有了:设置SQLServerCompactEditionUnderWebHosting的值为true则可,如:
AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);

加上这一句代码之后,就能正常使用SQLCE了。
?
?