EF6 SQL Server配置没有App.Config(Net461 / aspnetcore应用)



我正在将工作的ASP.NET MVC网站转换为ASP.NET Core网站。我正在尝试使应用程序无需app/web.config(似乎是ASPNETCORE应用程序的默认值),但是我的EntityFramework连接到SQL Server已损坏。一段时间后,我得到以下错误:

sqlexception:发生了与网络相关或实例特异性错误 在建立与SQL Server的连接时。服务器不是 发现或无法访问。验证实例名称是正确的 并且该SQL Server配置为允许远程连接。 (提供商:SQL网络接口,错误:26-定位错误 指定的服务器/实例)

因为我在ASP.NET核心网站中没有app.config/web.config,所以我使用DbConfiguration类告诉EF使用SQL Server:

public class SupportManagerDbConfiguration : DbConfiguration
{
    public SupportManagerDbConfiguration()
    {
        SetDefaultConnectionFactory(new SqlConnectionFactory());
        SetProviderServices(SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance);
    }
}
[DbConfigurationType(typeof(SupportManagerDbConfiguration))]
public class SupportManagerContext : DbContext
{
    public SupportManagerContext(string nameOrConnectionString) : base(nameOrConnectionString)
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<SupportManagerContext, Migrations.Configuration>());
    }
    public DbSet<User> Users { get; set; }
}
public class User : Entity
{
    public virtual string DisplayName { get; set; }
    [Required]
    public virtual string Login { get; set; }
}
public class Program
{
    public static void Main(string[] args)
    {
        var db = new SupportManagerContext("Server=(local);Database=SupportManager;Integrated Security=true");
        var user = db.Users.First();
        db.Dispose();
    }
}

,只要我将连接串保留在web.config(当然也包括ProvidErname)中,即使添加了dbConfiguration类,并且从添加了EntityFramework部分,此功能也可以在"旧的" ASP.NET网站上工作。旧网站的web.config。当我删除ConnectionsTring时,同一件事发生在旧网站中。

因此,基本上可能归结为缺少的Providername,但是我很难找到任何特定于此问题的东西。

经过大量反复试验,解决方案非常微妙。

SqlConnectionFactory具有第二个构造函数,上面有参数" baseconnectionstring"。如果我将其设置为Server=(local);Integrated Security=True,那么它将突然工作。MSDN上的文档记录了无参数构造函数的以下内容:

创建一个新的连接工厂,该工厂具有'data source =。 sqlexpress的默认基础连接属性;集成安全= true;多重反应ViverSultSets = true;'

显然不覆盖baseConnectionString是某种程度上阻止了这种情况,就像我预期的那样。但是,这仍然与配置有所不同,就像我通过Web/app.config所做的那样。

在旧项目的Web.config中,DefaultConnectionFactory设置为LocalDbConnectionFactory。这似乎真的很尴尬,因为我尝试使用实际的SQL Server数据库,但是在Web.config中使用时始终可以使用。因此,如下更改DbConfiguration类,通过代码提供相同的配置:

public class SupportManagerDbConfiguration : DbConfiguration
{
    public SupportManagerDbConfiguration()
    {
        SetDefaultConnectionFactory(new LocalDbConnectionFactory("mssqllocaldb"));
        SetProviderServices(SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance);
    }
}

最后,我对解决方案有些满意,因为它至少模仿了旧情况,即使它仍然不像我预期的那样容易。

最新更新