【问题标题】:Silverlight Entity Framework Dynamic Connection StringSilverlight 实体框架动态连接字符串
【发布时间】:2010-12-05 14:53:12
【问题描述】:

我在一堆不同的服务器上拥有相同的数据模型。我想根据我的用户是谁以及他们在做什么来动态创建一个连接字符串。

我的用户可以在多台服务器上拥有多个数据库。创建 DomainService 时,我需要一种干净的方式来构建连接字符串。

我看到 DomainService 有一个名为 CreateObjectContext() 的覆盖(从 LinqToEntitiesDomainService 继承),它允许我设置我想要的任何连接字符串,然后返回新实体并且生活很好。问题是, CreateObjectContext() 在构造函数之后被调用,所以我不能通过调用方法设置字符串。此外,我尝试在 DomainService 上创建一个新的参数化构造函数,但它从未被复制到客户端上的 DomainContext。

如果我能够提取连接字符串,CreateObjectContext() 会很好用,但由于我必须使用来自客户端的数据来确定要连接的数据库,这显然行不通。

我想得越多,就越觉得自定义构造函数正是我所需要的——只是不知道如何完成它。

我错过了什么?

【问题讨论】:

  • WCF 数据服务怎么样?

标签: silverlight entity-framework connection-string


【解决方案1】:

我找到了解决方案。有兴趣的可以看这里:

这感觉有点像 hack,但这是我能想到的唯一解决方案。感谢 forums.silverlight.net 上的 Sally Xu 提供的想法。

由于我的每个用户都可以在多台服务器上拥有多个数据库,因此我需要在第一次使用 DomainService 之前找到一种方法来创建 ConnectionString。每次用户从 UI 中选择一个新项目时,我都会设置一个这样的 cookie:

private void SetCookie(string cookieName, string cookieValue)
{
  DateTime expireDate = DateTime.Now + TimeSpan.FromDays(1); 
  string newCookie = cookieName + "=" + cookieValue + ";expires=" + expireDate.ToString("R");
  HtmlPage.Document.SetProperty("cookie", newCookie);
}

cookieName 是 SelectedProjectId,cookieValue 是我的 UI 中当前选择的项目。

然后我照常创建一个新的 DomainService,但我覆盖了CreateObjectContext()。这个方法在你第一次引用你的 DomainService 对象时被调用。我的覆盖看起来像这样:

protected override ProjectEntities CreateObjectContext()
{
  long projectId = -1;
  StringBuilder connection;
  if (System.Web.HttpContext.Current.Request.Cookies["SelectedProjectId"] != null)
  {
    projectId = Convert.ToInt64(System.Web.HttpContext.Current.Request.Cookies["SelectedProjectId"].Value);
  }
  else throw new Exception("Selected Project ID Exception");  // temporary

  // Verify this user has access to the DB just in case it's spoofed 

  // Lookup project ID in my database to get the database name and server name

  // Load template connection string found in web.config
  // Replace the template holders for SERVER_NAME and DATABASE_NAME with above lookup values

  return new ProjectEntities(MyDynamicConnectionString);      
}

再一次,这有点骇人听闻,但这是我能找到的为我的需要动态创建连接字符串的唯一方法。我希望这对其他人有帮助...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    相关资源
    最近更新 更多