我正在使用EF和DB First方法构建一个ASP.NET MVC3网站。我需要为用户提供一种可靠的运行时数据库上下文切换机制。我有几个数据库(相同的模式)用于远程"车间",公司总部的应用程序用户需要能够随时在数据库之间切换。
首先,我实现了一个基本控制器,它具有ChangeDbContext(字符串dbname)。它将选定的dbName持久化到Session,然后我在OnActionExecuting方法中从Session中检索。然而,它被证明是不可靠的,因为会话表现得不可预测(随机过期等)。所以我正在寻找一种聪明的方法来用其他东西替换会话。
我可以在以下方面提出建议:-EntityFramework对象初始化(BaseController Constructor?)放在哪里-我应该做什么额外的更改来利用WindowsAuth模拟数据库连接吗?
首先,您需要确保您的应用程序会话能够在重新启动和应用程序池回收后幸存下来。查看此
其次,您需要根据经过身份验证的用户请求为DBContext注入连接字符串。
我假设你有一个满是用户的数据库,所以你需要做的是在SQL表中保存一个可能的连接字符串列表,并将它们与关联的用户帐户关联起来。对用户进行身份验证后,需要检索与用户帐户关联的连接字符串您不希望将连接字符串存储在会话或任何其他可能向web客户端暴露敏感数据的机制中总之,这就是你需要做的。
- 您将希望根据经过身份验证的用户为每个请求检索连接字符串
- 将连接字符串注入DBContext
- 根据需要进行数据库调用
- 钱
将字符串注入实体很容易。
如果您首先使用的是EF 4.1代码,那么您的DBContext会是这样的。EF 4.1接受正常的ADO.NET连接字符串。
public class ExampleProvider : DbContext, IExampleProvider
{
private readonly string _nameOrStringConnection;
public ExampleProvider()
{
}
public ExampleProvider(string nameOrStringConnection)
: base(nameOrStringConnection)
{
_nameOrStringConnection = nameOrStringConnection;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Example>().ToTable("example");
modelBuilder.Entity<Example>().HasKey(x => x.ExampleId);
}
public DbSet<Example> Examples { get; set; }
}
如果您使用的是EF.edmx,您需要确保注入的连接字符串包括edmx元数据文件信息,如下所示。。。
"metadata=res:///ExampleModel.csdl|res:///EExampleModel.ssdl|res://*/ExampleModel.msl;…
如果您查看edmx设计器文件,您将看到DBContext有几个构造函数重载。根据需要使用第二个或第三个过载。
#区域上下文
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public partial class Entities : ObjectContext
{
#region Constructors
/// <summary>
/// Initializes a new Entities object using the connection string found in the 'Entities' section of the application configuration file.
/// </summary>
public Entities() : base("name=Entities", "Entities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
/// <summary>
/// Initialize a new Entities object.
/// </summary>
public Entities(string connectionString) : base(connectionString, "Entities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
/// <summary>
/// Initialize a new Entities object.
/// </summary>
public Entities(EntityConnection connection) : base(connection, "Entities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
#endregion
/// incomplete file
祝你好运!
Cookies可以长期保存,比会话长得多。您还可以查看隐藏的页面变量或损坏的URL。
1)会话不会过期或完成。。。但是在你在we.config中设置的时间之后…默认值是10分钟。Seesion必须过期,因为没有办法知道用户离开了我们的网站。。。所以,如果他们停止访问页面,比如说10分钟,我们假设,他们就会离开。。。这次你可以增加,但问题仍然存在。2) Tou可以直接将信息存储在cookie中。现在,由于cookie只会浪费浏览器上的资源(空间很小),您可以使cookie持久化。。。这样它就永远不会过期3) 作为cookie的替代方案,您可以将此信息与用户的凭据信息(登录名等)一起存储。您可以使用配置文件提供程序来定义属性DBChosen。