我正在尝试使用以下代码在启动时创建数据库:
class DataContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DataContext() : base("Database")
{
Database.Initialize(true);
}
}
/////////
try
{
var db = new DataContext();
db.Students.Add(new Student());
db.SaveChanges();
}
catch (Exception ex)
{
}
//的app.config
<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>
<connectionStrings>
<add name="Database"
connectionString="Server=(localdb)\v11.0;Integrated Security=true;
AttachDbFileName=C:\Users\Aaron\Documents\visual studio 2015\Projects\EF Test\EF Test\bin\Debug\MyData.mdf"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</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>
我认为我的连接字符串很糟糕。我已经试过了十几个没有运气的人。我在Initialize调用时遇到异常。 “尝试为文件附加自动命名的数据库失败”。谢谢你的帮助。
EDIT 改变了这个:
<connectionStrings>
<add name="Database"
connectionString="Server=(localdb)\v11.0;Integrated Security=true;
database=C:\Users\Aaron\Documents\visual studio 2015\Projects\EF Test\EF Test\bin\Debug\MyData.mdf"
providerName="System.Data.SqlClient"/>
</connectionStrings>\
现在我得到“附加信息:无法打开数据库”C:\ Users \ Aaron \ Documents \ visual studio 2015 \ Projects \ EF Test \ EF Test \ bin \ Debug \ MyData.mdf“登录请求。登录失败。“
答案 0 :(得分:0)
尝试
<connectionStrings>
<add name="Database"
connectionString="Data Source=(LocalDb);Database=MyData.mdf;Trusted_Connection=True" />
</connectionStrings>
答案 1 :(得分:0)
请参阅here.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="SchoolDBConnectionString"
connectionString="Data Source=(localdb)\v11.0;Initial Catalog=SchoolDB-ByConnectionString;Integrated Security=true"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
因此Code First将创建一个新的SchoolDB-ByConnectionString数据库。
答案 2 :(得分:0)
想出来。所以我在visual studio Server Explorer-&gt; Connect to database中创建了一个本地数据库。创建数据库后,我复制了如下所示的连接字符串:
<add name="dbtest" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Aaron\Desktop\mydb.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
和bam的工作就像一个魅力。谢谢大家的帮助。