我有一个控制台应用程序,我设法使用Code First创建数据库但我不能播种任何数据。我在Package Manager Console中使用update-database来完成它。请帮忙。我正在寻找几个小时。这是我的代码:
/ Models / ApplicationDbContext class:
namespace ToDoApp.Models
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext()
: base("ToDoApp")
{
Database.SetInitializer(new ApplicationDbInitializer());
}
public DbSet<TestModel> Tests { get; set; }
}
}
/ Models / ApplicationDbInitializer类:
public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
context.Tests.AddOrUpdate(new TestModel()
{
Description = "Test1"
});
base.Seed(context);
}
}
/ Models / TestModel类:
public class TestModel
{
[Key]
public int Id { get; set; }
public string Description { get; set; }
}
/程序类:
class Program
{
static void Main(string[] args)
{
Console.ReadLine();
}
}
/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>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
<!--<contexts>
<context type="ToDoApp.Models.ApplicationDbContext, ToDoApp">
<databaseInitializer type="ToDoApp.Models.ApplicationDbInitializer, ToDoApp" />
</context>
</contexts>--> <!-- This don't work -->
</entityFramework>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<appSettings>
<add key="DatabaseInitializerForType ToDoApp.Models.ApplicationDbContext, ToDoApp"
value="ToDoApp.Models.ApplicationDbInitializer, ToDoApp" />
</appSettings> <!-- This don't work also -->
</configuration>
答案 0 :(得分:0)
update-database
将运行迁移种子()。您的代码适用于初始化程序 Seed(),它仅在创建数据库时运行。有关差异的说明,请参阅here。
由于您使用DropCreateDatabaseAlways
,因此只要模型发生变化,它就会运行。你可以删除数据库。否则,强制进行模型更改,然后在代码中访问上下文或在启动时调用context.Database.Initialize()
。