首先,您需要確保您的應用程序會話可以在重新啓動和應用程序池回收後繼續運行。 See this
其次,你需要注入基於經過驗證的用戶請求你的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元數據文件信息...
...「元數據=資源:// /ExampleModel.csdl|res:// /ExampleModel.ssdl |資源://*/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
祝你好運!
聽到asp.net會話行爲是不可預知的並隨機過期是令人驚訝的! – chandmk