我正在将一个有效的ASP.Net MVC网站转换为ASP.NET核心网站。我试图让应用程序在没有App / Web.config的情况下工作(似乎是aspnetcore应用程序的默认设置),但我与SQL Server的EntityFramework连接已损坏。经过一段时间后,我收到以下错误:
SqlException:发生了与网络相关或特定于实例的错误 同时建立与SQL Server的连接。服务器不是 发现或无法访问。验证实例名称是否正确 并且SQL Server配置为允许远程连接。 (提供程序:SQL网络接口,错误:26 - 错误定位 指定的服务器/实例)
因为我在ASP.Net Core网站上没有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();
}
}
这在“老年人”中运作良好。 ASP.Net网站,只要我将ConnectionString保留在Web.config中(当然也包括providerName),即使添加了DbConfiguration类,并且从旧网站的Web.config中删除了EntityFramework部分。当我删除ConnectionString时,旧网站也会发生同样的事情。
所以基本上它可能归结为缺少的providerName,但我很难找到任何特定于此问题的内容。
答案 0 :(得分:0)
经过大量的反复试验,解决方案非常微妙。
SqlConnectionFactory
有第二个带参数'baseConnectionString'的构造函数。如果我将其设置为Server=(local);Integrated Security=True
那么它会突然起作用。 MSDN上的文档为无参数构造函数指出了以下内容:
创建一个新的连接工厂,其默认BaseConnectionString属性为'Data Source =。\ SQLEXPRESS;综合安全=真; MultipleActiveResultSets = TRUE;'
显然没有覆盖baseConnectionString
以某种方式阻止它像我预期的那样工作。但是,这仍然与配置不同,因为我将通过Web / App.config完成它。
在旧项目的Web.config中,DefaultConnectionFactory
设置为LocalDbConnectionFactory
。这似乎很尴尬,因为我正在尝试使用实际的SQL服务器数据库,但它在Web.config中使用时始终有效。因此,如下更改DbConfiguration
类通过代码提供相同的配置:
public class SupportManagerDbConfiguration : DbConfiguration
{
public SupportManagerDbConfiguration()
{
SetDefaultConnectionFactory(new LocalDbConnectionFactory("mssqllocaldb"));
SetProviderServices(SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance);
}
}
最后,我对这个解决方案有点满意,因为它至少模仿了旧的情况,尽管它仍然不像我预期的那么容易。