我正在为 MVC 应用程序创建 DataAccess C# 类库。在类库内部,我使用 EntityFramework 和 ASP.NET Identity。
当我尝试在类库上运行 Update-Database 或 Add-Migration 时,出现错误。
错误 26:建立与 SQL Server 的连接时发生了与网络相关或特定于实例的错误。服务器未找到或不可访问。
我从 IdentityUser 派生的 UserAccount 类如下:
public class UserAccount : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Address Address { get; set; }
public virtual PaymentDetail PaymentDetail { get; set; }
public virtual MediaResource ProfilePicture { get; set; }
public virtual ICollection<Conversation> Conversations { get; set; }
}
我的上下文类的实现使用了这个构造函数:
public class LouderContext : IdentityDbContext<UserAccount>
{
public LouderContext("DefaultConnection") { }
我的 App.config 文件的内容如下:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient"/>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v12.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
我尝试过的事情:
- 将连接工厂的参数从
v11.0
更改为mssqllocaldb
或v12.0
- 修复我的 visual studio 安装
- 手动将 SQL Server 对象资源管理器中的连接字符串添加到 App.config 中的连接字符串对象
我可以毫无问题地从 SSMS 访问 (localdb)\MSSQLLocalDB。我还可以通过脚手架 MVC 项目访问 LocalDb,但每当我尝试通过包管理器控制台在我的类库上运行任何命令时,我的问题仍然存在。似乎是什么问题?有什么明显的东西跳出来了吗?
最佳答案
EF 使用启动项目作为连接字符串的源,我认为这可能是您的问题,因为您的启动项目是 MVC 项目尝试将启动项目更改为类库,然后添加迁移和更新数据库。
编辑:
您有两个具有相同名称 DefaultConnection 的连接字符串,一个在 app.config 中,一个在 web.config 中,更改它并在 DBContext 构造函数中添加一个属于 app.config Ex : public LouderContext("AppConfigConnection") {
另一个解决方案:
Get-Help enable-migrations -detailed
您可以找到有关 -StartupProjectName 选项的文档:
-StartUpProjectName
Specifies the configuration file to use for named connection strings. If omitted, the specified project's configuration file is used.
这意味着如果您使用此选项指定项目名称,迁移将在指定项目的配置文件中查找连接字符串。 (配置文件可以是 web.config 或 app.config)。
关于c# - LocalDb 和 IdentityDbContext Entity Framework 错误 26,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34551912/