将连接字符串发送到 ApplicationDBContext

Send connection string to ApplicationDBContext

我已自定义 ApplicationDBContext class 以通过其构造函数接收连接字符串。直接调用时它可以连接到数据库,但是当通过 app.CreatePerOwnContext 调用时我无法调用它。我的 class 定义如下:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(string databaseConnection)
        : base(databaseConnection, throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create(string databaseConnection)
    {
        return new ApplicationDbContext(databaseConnection);
    }
}

问题出在下一行 Startup.Auth.cs 调用时。

app.CreatePerOwinContext(ApplicationDbContext.Create);

create 方法也接受一个连接字符串,但以下不起作用

app.CreatePerOwinContext(ApplicationDbContext.Create(connectionString));

它产生以下错误:

Error   1   The type arguments for method 'Owin.AppBuilderExtensions.CreatePerOwinContext<T>(Owin.IAppBuilder, System.Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

将连接字符串发送到 ApplicationDbContext class 以便 Owin 上下文可以引用它的正确语法是什么?

连接字符串正确,但为了完整起见,设置它的代码如下。

string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

请查看您正在使用的方法的declaration

public static IAppBuilder CreatePerOwinContext<T>(
    this IAppBuilder app,
    Func<T> createCallback) where T : class, IDisposable

它需要一个类型为 Func<T> 的参数。

因此您需要将代码更改为:

app.CreatePerOwinContext(() => ApplicationDbContext.Create(connectionString));