[英]DataException - Cannot attach file as database EntityFramework in C#
I was working on Console Application, before. 之前,我曾在控制台应用程序上工作。 I was able to access Database.
我能够访问数据库。 Today, I wanted to take one step further and added Web API project to my solution.
今天,我想更进一步,将Web API项目添加到我的解决方案中。 My main concern is to use the database I created for the first project.
我主要关心的是使用为第一个项目创建的数据库。 You can see the error I am getting below, later I will explain what I did so far:
您可以在下面看到我得到的错误,稍后我将解释到目前为止的操作:
DataException was unhandled by user code
用户代码未处理DataException
{"An exception occurred while initializing the database. See the InnerException for details."}
{“初始化数据库时发生异常。有关详细信息,请参见InnerException。”
So I looked the InnerException and 所以我看了InnerException和
InnerException: {"Cannot attach the file 'C:\\Projects\\BilyonerParse\\BilyonerParse.Web\\App_Data\\BilyonerParse.Database.FootballContext.mdf' as database 'BilyonerParse.Database.FootballContext'."}
InnerException:{“无法将文件“ C:\\ Projects \\ BilyonerParse \\ BilyonerParse.Web \\ App_Data \\ BilyonerParse.Database.FootballContext.mdf”作为数据库“ BilyonerParse.Database.FootballContext”附加。”}
So, step by step, I created new WebAPI project inside my solution then create a new Controller class and write only two methods(you can see it below). 因此,我一步一步地在解决方案中创建了一个新的WebAPI项目,然后创建了一个新的Controller类并仅编写两个方法(您可以在下面看到)。 Then I tried to connect existing Database from Tools->Connect to Database and with specifying the name of DB.
然后,我尝试从工具->连接到数据库并指定数据库名称来连接现有数据库。 Lastly, because I was getting error about name of the DB, I added to Web.Config what I had got in App.Config in the first project since it specify the EntityFramework rules.
最后,由于遇到有关数据库名称的错误,我将第一个项目在App.Config中获得的内容添加到Web.Config中,因为它指定了EntityFramework规则。
Please find the mentioned files below. 请在下面找到提到的文件。
The Controller class: 控制器类:
namespace BilyonerParse.Web.Controllers
{
public class FootballMatchesController : ApiController
{
[HttpGet]
[Route("")]
public List<FootballMatch> Get()
{
IFootballMatchRepository repo = new FootballMatchRepository(new FootballContext());
return repo.GetAllFootballMatches().ToList();
}
public FootballMatch GetFootballMatch(int id)
{
IFootballMatchRepository repo = new FootballMatchRepository(new FootballContext());
return repo.GetFootballMatch(id);
}
}
The Web.Config: Web.Config:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301879
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
The below part is taken from the App.Config in the first project: 下一部分取自第一个项目的App.Config:
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
Below you can find the project folders hiearachy 在下面您可以找到项目文件夹hiearachy
That is what I have done in total. 这就是我总共所做的。 I am asking because I could not resolve the problem.
我问是因为我无法解决问题。 Hope you can help me.
希望您能够帮助我。
Please let me know if you need more information&detail. 如果您需要更多信息和详细信息,请告诉我。
Thanks! 谢谢!
You don't have a connection string so EF is falling back to defaults. 您没有连接字符串,因此EF恢复为默认值。 Try adding a connection string with the name of your context:
尝试添加带有上下文名称的连接字符串:
<add name="FootballContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\BilyonerParse.Database.FootballContext.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"
/>
http://www.asp.net/mvc/overview/getting-started/introduction/creating-a-connection-string http://www.asp.net/mvc/overview/getting-started/introduction/creating-a-connection-string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.