Silverlight Entity Framework Dynamic Connection String

浪子不回头ぞ 提交于 2019-12-01 13:58:40

I found a solution. For those that are interested, here it is:

This feels a bit like a hack, but it's the only solution I could come up with. Thanks to Sally Xu over at forums.silverlight.net for the ideas.

Since each of my users can have mulitiple databases on multiple servers, I needed to find a way to create the ConnectionString before the DomainService was used the first time. Each time the user selects a new project from the UI, I set a cookie like this:

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);
}

The cookieName is SelectedProjectId and the cookieValue is the current selected project in my UI.

Then I create a new DomainService as normal, but I override CreateObjectContext(). This method gets called the very first time you reference your DomainService object. My override looks like this:

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);      
}

Again, this is a bit hackish, but it was the only way I could find to dynamically create a connection string for my needs. I hope this helps someone else...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!