Sco*_*ott 0 silverlight entity-framework connection-string
我在一堆不同的服务器上拥有相同的数据模型.我想根据用户是谁以及他们正在做什么来动态创建连接字符串.
我的用户可以在多个服务器上拥有多个数据库 在创建DomainService时,我需要一种干净的方法来构建connectoin字符串.
我看到DomainService有一个名为CreateObjectContext()的覆盖(继承自LinqToEntitiesDomainService),它允许我设置我想要的任何连接字符串,然后返回新实体,生活是美好的.问题是,CreateObjectContext()在构造函数之后被调用,所以我不能通过invoke方法设置字符串.此外,我尝试在DomainService上创建一个新的参数化构造函数,但它永远不会被复制到客户端上的DomainContext.
如果我能够拉取连接字符串,CreateObjectContext()会很好用,但由于我必须使用客户端的数据来确定要连接的数据库,这显然不起作用.
我越是想到它,我越觉得自定义构造函数正是我所需要的 - 只是无法弄清楚如何完成它.
我错过了什么?
我找到了解决方案.对于那些感兴趣的人,这里是:
这感觉有点像黑客,但这是我能想到的唯一解决方案.感谢Sally Xu在forums.silverlight.net上的想法.
由于我的每个用户都可以在多个服务器上拥有多个数据库,因此我需要在第一次使用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);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
同样,这有点hackish,但这是我能找到动态创建连接字符串以满足我的需求的唯一方法.我希望这有助于其他人......